0

Why doesn't True in Phyton? Help pls!

The following code should be True like in real life. :D 20*1.07==20+20*0.07 #False 20*1.07==20+20*7/100 #False 20+20*0.07==20+20*7/100 #True

3rd Oct 2022, 2:10 PM
Szilárd Orbók
10 Respuestas
+ 8
here are the results: 20*1.07==20+20*0.7 print(f'{20 * 1.07} == {20 + 20 * 0.7}') 21.400000000000002 == 34.0 -> False 20*1.07==20+20*7/100 print(f'{20 * 1.07} == {20 + 20 *7 / 100}') 21.400000000000002 == 21.4 -> False 20+20*0.7==20+20*7/100 print(f'{20 + 20 * 0.7} == {20 + 20 * 7/ 100}') 34.0 == 21.4 -> False
3rd Oct 2022, 2:59 PM
Lothar
Lothar - avatar
+ 7
Avoid comparing floats for equality. You will have rounding and precision problems. you can use math.isclose() and set your tolerance.. import math print(24.0001==24) print(math.isclose(24.0001, 24, abs_tol= 0.1 ))
4th Oct 2022, 12:54 AM
Bob_Li
Bob_Li - avatar
+ 6
Szilárd Orbók , if precission matters, we can use data type *decimal*. we have to import the modul. this number type has not the issue as floating point numbers.
4th Oct 2022, 4:56 PM
Lothar
Lothar - avatar
+ 3
The representation of floating point numbers is never perfectly accurate. So the equality comparison should not be used. If you want to allow for the possible tiny rounding error, as Bob_Li suggested use math.isclose() method. Alternatively you can also use Fraction or decimal types. https://davidamos.dev/the-right-way-to-compare-floats-in-JUMP_LINK__&&__python__&&__JUMP_LINK/
4th Oct 2022, 2:19 PM
Tibor Santa
Tibor Santa - avatar
+ 2
inputs are always string, you can cast it to int or float depending on your use case.
4th Oct 2022, 9:09 PM
Bob_Li
Bob_Li - avatar
+ 1
I just tested the code by assigning the evaluation results for the three expressions and they all are False ... Now I'm confused ...
3rd Oct 2022, 2:39 PM
Ipang
+ 1
Why doesn't True in Phyton? Help pls! The correct question is: 20*1.07==20+20*0.07 #False 20*1.07==20+20*7/100 #False 20+20*0.07==20+20*7/100 #True The original problem is 7 percent of something with different solutions.
3rd Oct 2022, 9:54 PM
Szilárd Orbók
+ 1
How to find data type when user enter number
4th Oct 2022, 7:08 PM
kailash kumar
kailash kumar - avatar
0
1{20*1.07=21.40000000000002 20+20*0.7=34.0 False} 2{20*1.07=21.4000000000000---2 20+20*7/100=21.4 False} 3{20+20*0.7=21.4000000000-----002 20+20*7/100=21.4 False}
3rd Oct 2022, 3:08 PM
Altair Enigma
Altair Enigma - avatar
0
In the first line 0.7 is 0.07. Just a typo. The results are same.
3rd Oct 2022, 9:46 PM
Szilárd Orbók