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.
Page Index Toggle Pages: 1
int vs float (Read 863 times)
int vs float
Oct 8th, 2009, 6:55am
 
I'm stuck in the section that "explains" the difference between integer and float. I've re-read the pages in the blue Processing textbook a couple times with no better understanding. and the whole thing with 4/3 = but 4.0/3 = error is just...whu...? Huh Can someone break it down to a childlike-level, please?

thank you
Re: int vs float
Reply #1 - Oct 8th, 2009, 7:49am
 
Let's try...

Integer numbers are whole: if you divide 11 men by 3, you will get 3 groups of 3 (computers like even quantities...) and 2 men remain on the side (that's the rest (?) not sure of English term).
So if you write int x = 11 / 3; x will get the value 3. It trips lot of people when they do eg. 5 / 10 and are surprised to get 0...
Note: you can use the modulus operation (%) to get the rest (remainder, no?). int r = 11 % 3; Also very useful to be sure a quantity remains inside bounds, but that's another story.

Float (floating-point) numbers have a decimal separator (decimal point in USA, decimal comma in France... Wink).
So you can get fractional quantities: you can divide 11 liters by 3 and get 3 times 3.667 liters (with a round up).

In Java, you mark float numbers by appending a f or F after them: 11F, 4.0f, 3.1415926535F... Otherwise, if they have a decimal point (no choice here, in the code at least), they will be double, ie. numbers that can be much bigger (or more precise) but takes more memory (and are longer to compute).
Processing made the choice to use (almost) exclusively floats, so behind the scene it appends automatically a f after all numbers with decimal point. You have to be explicit (4F, 11f) if you don't give the decimal point.
Writing float f = 55; works because the literal integer is automatically converted to float by Java compiler. But if you write float f = 4/3; f will get 1.0 because the division will be done by using integers first, and the result is then converted to float.
This can be avoided by writing: float f = 4.0/3; or float f = 4/3.0; or of course float f = 4.0/3.0; or by replacing the .0 by F.

I hope I haven't lot you in the explanations, perhaps a bit too detailed (and perhaps confuse...).
Re: int vs float
Reply #2 - Oct 8th, 2009, 7:15pm
 
I think that helped a lot. thank you!
Page Index Toggle Pages: 1