0

I want to calculate this second degree equation in python:

10^-6x^2 +10x + 10^-6 = 0

Using the known formula it would look like this in python:

#This is just a small part of the program#
a = 10.**-6
b = 10.
c = 10.**-6

square = sqrt((b**2) - (4.*a*c))
numerator1 = -b - square
numerator2 = -b + square
denominator = 2.*a

print square
print numerator1
print numerator2

Now to my question: Round off errors makes my

square = 10.0
numerator1 = -20
numerator2 = -1.98951966013e-13

Why is my second numerator so way off? -b is the same in both cases... This will make my x2 be calculated in the wrong way. How can I fix this round off error?

Crauth
  • 1
  • 1

2 Answers2

0

Your problem arises due to floating point precision issues. You can read up more on that here - https://docs.python.org/2/tutorial/floatingpoint.html

You can overcome this a bit by rounding -

>>> round(numerator2, 3)
-0.0
Shashank Agarwal
  • 2,769
  • 1
  • 22
  • 24
  • Yes, I tried this, but this would make x2 have no solution, but it should be -1e-07 ? – Crauth Sep 08 '14 at 18:11
  • I'm not sure I follow the problem. `numerator2 / denominator` gives me `9.947598300641403e-08`, which is very close to `-1e-07` (and then see my note on floating precision errors). The difference between the two numbers is `-5.239999999999986e-10` – Shashank Agarwal Sep 08 '14 at 18:30
  • Oh, sorry, I mixed up with another number I had earlier which was way off. But in any case, my problem: I want it to show exactly -1e-07 as answer, and not an extremely close number:) maybe I can find out how in the link you posted. Thank you! – Crauth Sep 08 '14 at 18:39
  • I doubt that you'll be able to get that exactly. `round(9.947598300641403e-08, 7)` gives `-1e-07`, but this might be a bit inflexible. – Shashank Agarwal Sep 08 '14 at 18:48
  • That's more than close enough:) Thanks a lot!! – Crauth Sep 08 '14 at 19:19
0

I believe you might find some answers in this post: Python rounding error with float numbers

Additionally, you should notice:

>>> print square 10

while

>>> square 9.999999999999801

Community
  • 1
  • 1
  • Yes I noticed this, and have been trying for hours to round of the square itself in the code so I could use it for all equations...to get a closer representation even when the square was a number that I could not represent with binary numbers. – Crauth Sep 08 '14 at 19:02