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?
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.
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.
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):
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.
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:
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With