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
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
+ 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 ))
+ 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.
+ 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/
+ 2
inputs are always string, you can cast it to int or float depending on your use case.
+ 1
I just tested the code by assigning the evaluation results for the three expressions and they all are False ...
Now I'm confused ...
+ 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.
+ 1
How to find data type when user enter number
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}
0
In the first line 0.7 is 0.07. Just a typo. The results are same.