Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can anyone explain this subtraction and summation in python? [duplicate]

Tags:

python

I'm a bit confused of how this subtraction and summation work this way:

A = 5
B = 0.1
C = A+B-A

And I found the answer is 0.099999999999999645. Why the answer is not 0.1?

like image 472
Erika Sawajiri Avatar asked Jun 19 '13 04:06

Erika Sawajiri


People also ask

How to subtract numbers in Python?

In this example, we will see how to subtract numbers in Python and see its various use cases. To subtract two numbers in Python, use the subtraction (-) operator.

What is the difference between list comprehension and sum () in Python?

The sum () is used to perform sum of list. List comprehension is just the shorthand technique to achieve the brute force task, just uses lesser lines of codes to achieve the task and hence saves programmers time. The sum () is used to perform sum of list.

How to subtract two float numbers using a function in Python?

Here, we can see program to substract two float number using a function in python. In this example, I have used the input () method. To take the inputs from the user. The float data type is used to enter the decimal numbers as the input. I have defined a function called subtraction as def subtraction (a,b):

How to sum a list of lists in Python?

We can achieve this task by iterating through the list and check for that value and just append the value index in new list and print that. This is the basic brute force method to achieve this task. The sum () is used to perform sum of list.


2 Answers

This is a floating point rounding error. The Python website has a really good tutorial on floating point numbers that explains what this is and why it happens.

If you want an exact result you can:

  • try using the decimal module
  • format your result to display a set number of decimal places (this doesn't fix the rounding error):

    print "%.2f"%C

I also recommend reading "What Every Computer Scientist Should Know About Floating-Point Arithmetic" from Brian's answer.

like image 153
John Lyon Avatar answered Sep 23 '22 20:09

John Lyon


Why the answer is not 0.1?

Floating point numbers are not precise enough to get that answer. But holy cow is it ever close!

I recommend that you read "What Every Computer Scientist Should Know About Floating-Point Arithmetic"

like image 20
Brian Cain Avatar answered Sep 23 '22 20:09

Brian Cain