+ 11
Could anyone tell me why the output of this code is 5.19999...? I was expecting just a simple 5.2
18 Réponses
+ 8
I know that you fixed it already, though for the benefit of others, here is what I noticed in the code. In the inner loop there is a line that incrementally adds a floating point value.
valueToCheck = valueToCheck + stepSize;
Repeatedly adding a float can accumulate a small rounding error with each addition (technically, it is called aliasing error). Here, the value in stepSize does not change in the inner loop. Because of that, you can improve the chance of getting the right outcome by using a whole number loop counter and then multiplying the counter by stepSize.
Viz:
valueToCheck = (++counter)*stepSize;
I tried such a modification to your program and got exactly 5.2 in the output. It is a slower operation, but may be necessary if precision is critical.
+ 7
Calviղ why:
alert (bottomValue.toFixed(10));
//5.2000000000
and not:
alert (bottomValue.toPrecision(2));
//5.2
🤔
+ 5
Really useful answer. Thanks a lot ~ swim ~
+ 5
will you could use toPrecision method too. Just bear in mind toFixed sets numbers of displayed digits after decimal point, whereas toPrecision sets total number of dispalyed digits, so you have to adjust the parameters if there is more decimal digits.
+ 4
Excellent contribution Brian . Definitely makes sense and really helpful
+ 4
Ah, I see now Calviղ , gotcha, thanks for pointing out the distinction 😊
+ 4
Really interesting stuff and all good contributions. Thanks a lot to everyone.
This was a bit of code I was using in a challenge code exercise. Feel free to have a look on the link
https://code.sololearn.com/WugWI9DxG2aG/?ref=app
+ 3
My Javascript is rusty but I was also able to solve/fix issue using the info from the link, thanks for sharing ~ swim ~ 👍
+ 3
Use
alert (bottomValue.toFixed(10));
+ 3
What is Gui
+ 2
Isn’t 5.1999999 almost 5.2, but just .000001 off? (Numbers were guessed, but I hope you get the point)
+ 2
Coz 0 dont 1na wanna go
+ 2
~ swim ~ Yay, this site seems really interesting! Thank you!
- 2
Do any of you know the answer to this code:”hello world!”