Weird math in 'for' loop!


#1


https://www.codecademy.com/en/courses/javascript-beginner-en-ASGIv/2/4?curriculum_id=506324b3a7dffd00020bf661


I made the three loops: for, while and do-while, with adding some numbers (I know, very creative). The for loop just lists the current value of i and adds 4,6 to it. But the outcome is weird! The numbers that are printed are:
1. 0
2. 4.6
3. 9.2
4. 13.799999999999999
5. 18.4
And there were more of those super long ones 'cause I originally made it run until it reached 200, but that was a lot and I deleted that zero. Why does this happen?
Here's the code for this loop:

for (var i=0; i<20; i+=4.6)
{
    console.log(i);
};

#2

Right now your i is increasing by 4.6 and then printing each time. (i: i = 0, i = (0)+4.6, i = (0+4.6)+4.6...)

I see two ways to make it list (4.6, 5.6, 6.6...).
You can have i increase by one and then add 4.6 just before printing (i+4.6: 0+4.6, 1+4.6, 2+4.6...)
Or you can change your starting point from 0 to 4.6 and have i increase by one (i: 4.6, 5.6, 6.6...)


#3

Here is the explanation:
http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html

Found on:


#4

Yes, it is increasing by 4.6, that's what I wanted and that's what I wrote. I don't want it to increase by one, that would be boring, haha (especially in the first version where it went to 200, that would've taken forever!). My question was about those very many digits after the decimal point.


#5

So...there is no simple answer? I mean the answer to this, as well as many other issues, is probably somewhere in there, but it requires a lot of initial knowledge to even try to understand any of it.

edit: Okay I didn't go to the stackoverflow at first, but I'm guessing the answer is "this happens because JS uses floats by default and floats are crazy and inaccurate"?


#6

Sorry, I completely misinterpreted your post! You're right - those decimals are crazy. It has something to do with floats and .3 being a common representation of .3333..., but unfortunately I'm no floats expert.


#7

in general, floats weren't ever great for keeping whole numbers, they are always off by very small number.
you'd end up with number like 4.99999999999.

http://effbot.org/pyfaq/why-are-floating-point-calculations-so-inaccurate.htm


#8

Thank you! That was much easier to parse!


#9

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.