0
Don't understand the correct answer in JS challenge
Hello, I stormed a few javascript challenges to get Level 15, and there was a question and an answer to it that I don't really understand. I'm probably just stupid, but could you please help? Here's the question: What's the output of this code? var num1 = 0.1, num2 = 0.2, num3 = 0.3; console.log(num1 + num2 == num3) Correct answer: false My and opponent's answer: true
5 Réponses
+ 2
That's because of floating point issues in how they actually stored in memory..
These type question should not asked in quizzes... But in this way it help to more about....
num1 + num2 (floating point arithmetic) result slitely higher or lesser value in floating point arithmetic because internal convertion when storing results like it returning 0.3000000000004 value so which is not equal to 0.3 so resulting false... It difficult to calculate exact value there..
Edit:
Qui-Gon Jinn
See this for more:
https://floating-point-gui.de
http://effbot.org/pyfaq/why-are-floating-point-calculations-so-inaccurate.htm#:~:text=It's%20a%20problem%20caused%20by,resulting%20in%20small%20roundoff%20errors.
0
num1 + num2 = 0.30000000000000004
obvious not equal to num3
because of float point with finite bits.
0
Dear friend firs of all you can search such problem, there are a lot same questions with answer.
But in fact remeber acsioma of programming NEVER compare double, or float numbers with == or != The problem is pc construction. Since there binary system in pc there are some epsilon during plus the numbers
0.1+0.2 is = 0.30000....1 and comparison of this gives problem
0
Sol always when you use floating, use epsilon for example 1e-10 and compare with a+e >b or and etc. For example to check if numer less or equal 0 you need fabs(a) <1e-10 or <1e-16. In fact may be you have 0.0000000000000001 but in fact it is 0. so 1e-10 will be epsilon
0
Jayakrishna🇮🇳 Thank you very much :)