More on Control Flow in JS: 3. For or while: decimal arithmetic errors


#1

https://www.codecademy.com/courses/javascript-beginner-en-qDwp0/0/3?curriculum_id=506324b3a7dffd00020bf661

Hi. This exercise required me to write basically any for or while loop that runs without error. What I wrote should work "in theory," but actually causes an infinite loop. I remembered once seeing a weird result like 0.5 + 0.5 = 1.00000000000000000000001 or something, so I suspected this to be the cause.

I could multiply all the numbers in the for(...) statement by 5, and then divide by 5 somewhere in the code within the loop, but for longer codes that's quite a hassle and I imagine some precision might be lost somewhere...

My question is, does anyone know any beginner-friendly reading material with guidelines on how to work with decimals in JavaScript, to avoid this kind of error?


for(var i = 1; i; i -= 0.2) {
    console.log(i);
}


#2

Error is one word, perhaps, but floating point evaluation is the only real way to descibe it. There are no decimal fractions in binary arithmetic, hence the need for the very complex arithmetic that must be carried out by the computer. Any multiplication or division operation is prome to tiny errors (in the range of 10 to the minus14 or minus15) that show up in the returned result. This is known as floating point error and of no consequence, given that we can fix the returned value.

 > math.pi
=> 3.1415926535897931
 > math.e
=> 2.7182818284590451
 > math.pi / math.e
=> 1.1557273497909217
 > math.e / math.pi
=> 0.86525597943226507
 > math.pi / math.e * math.e / math.pi
=> 1.0

Oops. That's Pythonic. Here is the JavaScript console way:

     > pi = Math.PI
    => 3.141592653589793
     > e = Math.E
    => 2.718281828459045
     > pi / e
    => 1.1557273497909217
     > e / pi
    => 0.8652559794322651
     > pi / e * e / pi
    => 1

#3

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