We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpPrograms › Very simple question.  Divide operation
Page Index Toggle Pages: 1
Very simple question.  Divide operation (Read 798 times)
Very simple question.  Divide operation
Jul 29th, 2005, 1:27am
 
I have:
Code:

float y = 1/2;
if(y==0.5) print("Success. Y = "+y);
else print("Fail. Y = "+y);

Why is a simple fraction value like that rounded?
If I do this:
Code:

float x = 1;
float y = x/2;
if(y==0.5) print("Success. Y = "+y);
else print("Fail. Y = "+y);

Everything works as it should be.
What's going on?  Is this a fundamental flaw, or am I just missing something too obvious?

Re: Very simple question.  Divide operation
Reply #1 - Jul 29th, 2005, 1:51am
 
it's because in the first example, integers are used, and they don't become a float until they get to the lefthand side of the equals sign:

float y = 1/2;

so 1 is divided by two, and then the result of that integer division is assigned to a float.

to make it easier to compare, your second example is equivalent to writing:

float y = 1.0/2;

in which case, java sees that 1.0 is a float, so it also converts 2 to a float so that they can be divided, which makes it identical to:

float y = 1.0/2.0;

and because floats are being used on the righthand side, the result will be a float, even before it gets to the lefthand side.
Re: Very simple question.  Divide operation
Reply #2 - Jul 29th, 2005, 4:08pm
 
i've just added this to the FAQ as well since it's a common problem:  
http://processing.org/faq/bugs.html#integers
Re: Very simple question.  Divide operation
Reply #3 - Jul 29th, 2005, 11:09pm
 
Thank you so much! Is this unique to java, or common for many languages nowadays?
Re: Very simple question.  Divide operation
Reply #4 - Jul 30th, 2005, 12:35am
 
Most languages use what is known as strong typing, e.g. an integer is an integer, and a float is a float, and rarely get magically converted unless you ask nicely.

There are however quite a few languages, which place less importance on the "type" of a variable,a nd let you work on them as if they're an int, float, string or whatever, which can sometimes be useful, but can lead to problems when you or the language get confused as to what it should be treated as, and do the wrong thing...
Page Index Toggle Pages: 1