This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 6 years ago.
Am working on a small math-checker using Python and everything works well except of divisions.
Problem: The quotient with two decimals (2/3 = 0.67), float, is equal to an input (0.67). But the if-statement I use to compare a user's input with the result says it isn't equal.
Assumption: the problem is related to float.
My code:
result = float(value0 / value1)
result = round(result,2)
value3 = input("Number 1")
value3 = float(value3)
if result != value3:
print "Wrong!"
print result
elif result == value:
print "Right!"
Of course I could create a function with a different approach, but I am curious to understand why it doesn't work.
If there's a similar thread, please post the link and close this one. Thanks for any help.
when checking floats for equality always use
equal_threshold = 1e-5
if abs(result-value)<equal_threshold:
Related
This question already has answers here:
Is floating point arbitrary precision available?
(5 answers)
Is floating point math broken?
(31 answers)
Closed 1 year ago.
I am trying to divide floats by each other but am having a hard time getting accurate results. I understand that computers store floats in a way where the value stored is not exact to the given number. I am simply looking for a way where I can get specific results when working with floats.
input:
x = 2.4
y = 0.2
print(x/y)
Output:
11.999999998
I highly recommend to use decimals
Example
from decimal import Decimal
x = Decimal("2.4")
y = Decimal("0.2")
print(x / y) # 12
Notice we passing number as string, as passing float numbers would have the same problem you pointed out.
But care with comparison, as 12 == x / y evaluates to False
This question already has answers here:
Python floating point number comparison
(3 answers)
Closed 5 years ago.
I write below program but My program cannot check the two number is equal or not.
There is no error,
I would be appreciate for any help.
import math
def IsCollinding(ball1,ball2):
distance=math.sqrt((((ball2[0]-ball1[0])**2)+((ball2[1]-ball1[1])**2)))
print(type(distance))
print(type(ball1[2]+ball2[2]))
if(distance==ball1[2]+ball2[2]):
print("Is Coliding")
else:
print("Not Coliding")
print(distance)
print(ball1[2]+ball2[2])
ball1=[2,2,3]
ball2=[11,11,9.7279220614]
IsCollinding(ball1,ball2)
output:
<type 'float'>
<type 'float'>
Not Coliding
12.7279220614
12.7279220614
You can not really do this. Floats may appear equal, but are actually different due to floating point precision. However, you can cheat. We can call two numbers "equal" if the difference between the two is very small.
The function looks like this:
(x - y) < delta
Where delta is a small number. Implemented in Python:
def almost_equal(x, y, delta=1e-10):
return abs(x - y) < delta
I use abs here to get the absolute value of the difference. We avoid having to deal with negative numbers and the order of the x and y arguments this way.
Comparing two floats is one of the most common gotchas, and is something most of us run into at one point. Googling "comparing two floats python" should have returned plenty of informative results about this topic.
This question already has answers here:
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
Closed 6 years ago.
I am trying to do the calculation
Using the python decimal module with the following code:
from decimal import *
getcontext().prec = 9
sum = Decimal(0)
for i in range(1,11):
sum += Decimal(1/(i**4))
print sum
however, this outputs 1, not a very small fraction like I would expect. I can't find much information here https://docs.python.org/2/library/decimal.html about what is wrong with the code. My guess is sum is not being used as a Decimal in the loop, but I am unsure how to resolve that.
If you use Python 2.x, then in the expression: 1/(i**4), the integer devision is used, as result for i=1, it equals to 1 and for all other i>1, it gets 0.
Just add floating point to 1: 1./(i**4), this should fix the problem.
PS In Python 3.x, your code should work as expected, because operator / is defined on floating point numbers, while operator // is defined for integers.
First of all, don't use sum as a variable name, as it is a built-in.
And its sort of necessary to provide at least one float for arithmetic if you expect a float-type answer, here:
s = Decimal(0)
for i in range(1,11):
s += Decimal(1./(i**4)) # dividing 1. or 1.0 instead of just 1
print s
this gives:
1.08203658
This question already has answers here:
Can't convert string number value to float
(3 answers)
Closed 7 years ago.
I seem to have a problem with my code for a simple calculator with equations already codded into it that rounds to decimal points. The problem i have is that I have a variable that has a number from an equation but it isn't rounding to the nearest 2 decimal points when it needs to. Here is an example code:
def main():
variable1 = input("Input number")
variable2 = input("Input number")
V1 = float(variable1)
V2 = float(variable2)
variablesq = V1*V1
equation = 20242*(V2/variablesq)
answer = equation
round(answer, 2) #This is where the problem is occurring
print Answer
I do believe my mistake is that I'm using a variable instead of a set number but say the answer is 15.2353 it won't round the number from the variable to 15.24
Just calling the function won't do anything. You need to assign the result to something.
answer = round(answer, 2)
You can simply do "{0:.2f}".format(answer) that way you don't need to assign it to a variable.
This question already has answers here:
Why does integer division yield a float instead of another integer?
(4 answers)
Closed 8 years ago.
While solving Project Euler problems with Python (which I am a beginner at), I got this following error. The question is to find the sum of the digits of 2^1000. For that I wrote the following code :
sum=0
x=2**1000
while(x):
sum += x%10
print(sum) #Just to check whats happening
x /= 10
print("\n"*5)
print("Sum = ",sum)
For this, I get decimal added up somewhere in between.
Output :
6
10.0
10.0
12.0
16.0
....
1116.0
1122.0
1131.625 #Why does the decimal get added?
1138.59375
.....
1181.495136589947
1186.5812084526442
1188.089815638914
1195.240676357541
1195.9557624294036
1197.0272710365898
1197.1344218973084
1197.1451369833803
1197.1462084919874
.....
1197.1463275484991 #This number gets repeated a lot of times
1197.1463275484991
1197.1463275484991
Sum = 1197.1463275484991
Please explain what's going on and help.
Use integer division instead of floating point:
x //= 10
Do not know if you're looking for an alternative implementation, but this might be more straightforward if you don't want to risk crossing over into floating point land.
# Python 2.7
x = str(2**1000)
print sum([int(i) for i in x])