You don't receive -8
, you receive -8.XXXXXXe-17
. Note the e-17
at the end. That's scientific notation, so your number is actually -0.00000000000000008XXXXX
. You can see the float number without scientific notation using angle.toFixed(20)
. The number is the amount of decimals that you want to show.
Why you get such small numbers if you are only increasing and decreasing by 0.01
? may you ask. This happens because floating points are not exact as decimals are impossible to be "saved to the end", not like integers. Think of 1/3
having an infinite numbers of decimals, for example. Here you can read more about JavaScript and float precision: Dealing with float precision in Javascript
The other problem is having a negative angle (such small, but still negative although you actually check for negative angles). This happens because you check for negative angles BEFORE increasing/decreasing it, so if you have your multiplier as negative and your angle as, let's say, 0.0001whatever
(because of the float precision problem), it is still above zero, so you multiplier is still going to be negative, but is actually bigger than your angle, so when the multiplier is applied, the angle will be negative.
I can think of this way to solve this problem:
let angle = 0
let multiplier = .01
function raf() {
angle = angle+multiplier;
if(angle > 1 || angle < 0) {
multiplier = -multiplier
angle = angle<0?0:1;
}
console.log(angle.toFixed(20))
requestAnimationFrame(raf)
}
requestAnimationFrame(raf)
With this, you check if your angle is inside the limits AFTER working on it, so you will overcome the precision problem: https://codepen.io/anon/pen/eWppGy
Another way can be to use integers (because they don't have the precision problem, as I stated above) and divide the angle by 100 when going to work with it, like this:
let angle = 0
let multiplier = 1
function raf() {
angle = angle+multiplier;
if(angle >= 100 || angle <= 0) {
multiplier = -multiplier;
angle = angle<=0?0:100;
}
console.log(angle/100)
requestAnimationFrame(raf)
}
requestAnimationFrame(raf)
Pen: https://codepen.io/anon/pen/XRmmVq