Reputation: 1293
I'm trying to create a program for the visible-lines problem (sort of a simplified 2-D hidden surface removal, but that's beside the issue).
The problem I'm facing is that different parts of my program are generating different float values for what should ideally be identical scenarios.
For example, if I compute the intersection of two lines:
L1 : y = -92412.89517023x + -27156.376502560393
L2 : y = 75611.15200259097x + 90038.63242234234
I get the point
(-0.6974895016328344, 37300.64769417069).
But, when I actually compute the y values for these lines individually at x = -0.6974895016328344, I get 37300.64769417069 and 37300.64769417068 (notice the difference in the last digit).
Since I then go on to do comparisons with these different co-ordinates, I get incorrect answers (since logically the two should be same but the code actually ends up with different values).
How can I fix this?
Here's my code for the above mentioned functions (lines are represents as [m,c] for y = mx + c)
For intersection:
def intersection(line1, line2):
[line1, line2] = sorted([line1, line2])
if line1[0] == line2[0]:
print("INVALID")
m1, c1, m2, c2 = line1[0], line1[1], line2[0], line2[1]
x = (c2 - c1) / (m1 - m2)
y = (m2 * c1 - m1 * c2) / (m2 - m1)
print('interstection', line1, line2, x, y)
return [x, y]
For getting y-coordinate of a line from x-coordinate:
def gety(x, line):
return line[0] * x + line[1]
Upvotes: 1
Views: 460
Reputation: 31524
Floating point numbers could be different than expected due to the way they are stored in memory.
>>> 0.1 + 0.2
0.30000000000000004
So you should avoid comparing them without allowing an error.
>>> a = 0.1 + 0.2 # 0.30000000000000004
>>> a == 0.3
False
It's better do something like:
>>> epsilon = 1e-9
>>> abs(a - 0.3) <= epsilon
True
Upvotes: 3