+ 11

Could anyone tell me why the output of this code is 5.19999...? I was expecting just a simple 5.2

https://code.sololearn.com/W5Jqui9M3NHQ/?ref=app

29th Oct 2019, 8:41 PM
Fran Extremera
Fran Extremera - avatar
18 Respuestas
+ 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.
30th Oct 2019, 6:16 AM
Brian
Brian - avatar
+ 7
Calviղ why: alert (bottomValue.toFixed(10)); //5.2000000000 and not: alert (bottomValue.toPrecision(2)); //5.2 🤔
30th Oct 2019, 3:41 AM
will
will - avatar
+ 5
Really useful answer. Thanks a lot ~ swim ~
29th Oct 2019, 9:28 PM
Fran Extremera
Fran Extremera - avatar
+ 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.
30th Oct 2019, 7:33 AM
Calviղ
Calviղ - avatar
+ 4
Excellent contribution Brian . Definitely makes sense and really helpful
30th Oct 2019, 6:47 AM
Fran Extremera
Fran Extremera - avatar
+ 4
Ah, I see now Calviղ , gotcha, thanks for pointing out the distinction 😊
30th Oct 2019, 11:17 AM
will
will - avatar
+ 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
31st Oct 2019, 7:04 PM
Fran Extremera
Fran Extremera - avatar
+ 3
My Javascript is rusty but I was also able to solve/fix issue using the info from the link, thanks for sharing ~ swim ~ 👍
29th Oct 2019, 9:25 PM
will
will - avatar
+ 3
Use alert (bottomValue.toFixed(10));
30th Oct 2019, 12:50 AM
Calviղ
Calviղ - avatar
+ 3
What is Gui
31st Oct 2019, 10:34 AM
Ashok Kumar
Ashok Kumar - avatar
+ 2
Isn’t 5.1999999 almost 5.2, but just .000001 off? (Numbers were guessed, but I hope you get the point)
30th Oct 2019, 7:26 PM
Jake
+ 2
Coz 0 dont 1na wanna go
30th Oct 2019, 11:38 PM
Haruna Imam
Haruna Imam - avatar
+ 2
~ swim ~ Yay, this site seems really interesting! Thank you!
31st Oct 2019, 1:15 PM
Jonas Ferraz
Jonas Ferraz - avatar
- 2
Do any of you know the answer to this code:”hello world!”
1st Nov 2019, 3:38 PM
Madison Robinson
Madison Robinson - avatar