# 3/14 What is Happening?

#1

I made my computer type the numbers from 1 to 10 using this code:

``````for (i=0.1;i<1;i+=0.1){
console.log(i*10);
}``````

it showed up like this:

``````1
2
3.0000000000000004
4
5
6
7
7.999999999999999
9
9.999999999999998``````

What is happening?

#2

What you are seeing is a result of the method by which a computer (a binary engine) works with decimal fractions. Numbers between 0, inclusive, and 1, exclusive, are called floating point numbers or floats, for short.

The computer must perform a complex algorithm to convert decimal values to binary, complete the computation (in this case multiplication which is recursive addition) and then convert the result back to decimal. This is known as floating point arithmetic. There is a smidgen of error, as we can see, but it is very tiny, 1 to 4 parts in a million-billion.

We can mitigate this result by calling up the `Math.round()` method on our computed number.

``console.log(Math.round(i * 10));``

#3

Rounding. As you might have heard, your computer is not calculating with decimal numbers (0,1,2,3,4,5,6,7,8,9) like you do but with binary numbers (0,1) meaning instead of 5 your computer would write 101 which stands for:

``1*2^2 +0*2^1+1*2^0 = 4 + 0 + 1 = 5``

Now for fractional numbers like 0.1 its quite similar here you go on with negativ exponential e.g.

2^-1 = 1/2 = 0.5
2^-2 = 1/4 = 0.25
2^3 = 1/8 = 0.125

Try it and you'll find out that 0.1 is not as easy to be represented in base2 than it is in base10 so as the memory space per number is limited the computer stops after some accuracy and simply guesses the last number and so you might get rounding errors. If you're interested in this topic you can google for IEEE754 or have a look at the ecmascript standard to see how JS represents its numbers as it partially uses the IEEE754 and some other stuff. But also without knowing this you could keep in mind that the precision of your computer is limited and thereby rounding error may occur.