Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Basic subtraction error
#1
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
Reply
#2
https://docs.python.org/3/faq/design.htm...inaccurate
https://docs.python.org/3/tutorial/floatingpoint.html
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#3
So there is no way to print precisely 1.30 or the correct answer in any case?
Reply
#4
Use Decimal
https://docs.python.org/3.7/library/decimal.html
Reply
#5
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}')
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Error on basic Post API, FastAPI marlonbown 1 2,176 Nov-10-2022, 10:02 AM
Last Post: Larz60+
  forloop to compute sum by alternating from addition to subtraction JulianZ 3 1,804 Apr-02-2022, 09:36 AM
Last Post: DeaD_EyE
  List index out of range error when attempting to make a basic shift code djwilson0495 4 2,984 Aug-16-2020, 08:56 PM
Last Post: deanhystad
  Odd numpy error with subtraction DreamingInsanity 5 2,711 Jun-01-2020, 02:49 PM
Last Post: DreamingInsanity
  How to make a subtraction within a range of numbers? Alberto 3 10,089 May-08-2017, 09:13 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020