+ 2

[Solved] Why would (40 + 2*5)*1.1 output 55.0000...01 in Python?

n = int(input()) tcost = (40 + 5*n)*1.1 print(tcost) input 2 and you get: 2 55.00000000000001 [Program finished] EDIT: Sorry for the title typo (was 50.00...01 earlier) https://code.sololearn.com/cO7g469R7nle/?ref=app

23rd Mar 2022, 9:47 PM
Korkunç el Gato
Korkunç el Gato - avatar
5 odpowiedzi
+ 2
Its a rounding error due to the way a computer processes data. (Truncation Error) In this specific code, the computer uses a series addition numerical method to solve power to 1.1 Use math libraries to solve for exponents or use string manupulation to restrict (round) your answer print("%.2f" % tcost) Or print(round(tcost, 2))
23rd Mar 2022, 10:50 PM
Areeb Qureshi
+ 1
Not sure if this would work, but try changing 40 and 5 to 40.0 and 5.0 respectively, and make n floating point instead of int
23rd Mar 2022, 9:55 PM
Leonardo Amaro
Leonardo Amaro - avatar
+ 1
Leonardo Amaro Thanks, I will do that but lol this is weird Update: output's the same
23rd Mar 2022, 9:57 PM
Korkunç el Gato
Korkunç el Gato - avatar
+ 1
https://docs.python.org/3/tutorial/floatingpoint.html Says due to the approximations made to translate human decimal system to computer's binary system vice versa, aka base2 <-> base 10 equivalence so it has to do with how computers compute rather than python. (typed 0.00000000000001 and added python and got a reddit page that linked to this, I just couldn't find a phrasing to search about it other than this and didn't think I'd get a result at all, so I am sorry, but I hope that it'll at least turn out useful)
23rd Mar 2022, 10:16 PM
Korkunç el Gato
Korkunç el Gato - avatar
0
Areeb Qureshi Thanks a bunch about the information, I wouldn't know how to search about it. It's not the power operator that I used but simply multiplication. I'm guessing it's the same error by name, though. Either way, very good to know! I did use round later on btw :-)
23rd Mar 2022, 10:57 PM
Korkunç el Gato
Korkunç el Gato - avatar