Python Forum
Basic subtraction error - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Basic subtraction error (/thread-21707.html)



Basic subtraction error - rix - Oct-10-2019

I'll show it with some code:

Var1=str(input("What is Var1?")
#For example user inputs 8.10
Var2=str(input("What is Var2?")
#For example user inputs 6.80
Var1=float(Var1)
Var2=float(Var2)
Var3=Var1-Var2
print(Var3)
#The program then prints 1.2999999999999998
So the problem is it prints 1.2999999999999998 which is incorrect, as the correct answer is 1.30
My goal is to make it actually print the correct answer (for example if the user input 5.70 as Var1 and 3.90 as Var2, the correct answer would be 1.80)as I am creating a script to solve simultaneous equations.
Please let me know where I went wrong or how to make it print the correct answer if you know, thanks Smile


RE: Basic subtraction error - buran - Oct-10-2019

https://docs.python.org/3/faq/design.html#why-are-floating-point-calculations-so-inaccurate
https://docs.python.org/3/tutorial/floatingpoint.html


RE: Basic subtraction error - rix - Oct-10-2019

So there is no way to print precisely 1.30 or the correct answer in any case?


RE: Basic subtraction error - jefsummers - Oct-10-2019

Use Decimal
https://docs.python.org/3.7/library/decimal.html


RE: Basic subtraction error - buran - Oct-11-2019

Firts, your original code - no need to wrap input() function in str(). input() returns str in any case.

As suggested by jefsummers - you can use Decimal, instead of float
from decimal import Decimal
var1=Decimal(input("What is Var1?"))
#For example user inputs 8.10
var2=Decimal(input("What is Var2?"))
#For example user inputs 6.80
var3 = var1 - var2
print(var3)
Another option is to use string formatting when printing the result of deduction
var1=float(input("What is Var1?"))
#For example user inputs 8.10
var2=float(input("What is Var2?"))
#For example user inputs 6.80
var3 = var1 - var2
print(f'{var3:.2f}')