##### Python gives " -0.0 " as solution for an equation
 Python gives " -0.0 " as solution for an equation akar Unladen Swallow Posts: 3 Threads: 2 Joined: Aug 2020 Reputation: Aug-27-2020, 11:15 AM Hi, I'm learning Python (3.7) and I have sometimes strange results, for example when using code to find the real roots of a single univariate quadratic function: ```a= -200 b = 600 c = 0 discr = b**2 - 4 * a * c if discr < 0: print("This equation has no real root") elif discr == 0: print("This equation has one real root:\n" f"\t{-b / (2 * a)}") else: print("This equation has two real roots:\n" f"\t{(-b + discr**0.5) / (2 * a)}\t and\n" f"\t{(-b - discr**0.5) / (2 * a)}") ```returns ``````Output:This equation has two real roots: -0.0 and 3.0``````From what I could try, results are similar in other cases where 0 is a solution and a is negative (it's like "0" takes its sign from "a"), if "a" is positive then it returns "0.0". Isn't it a bit weird? Is there an easy/clean/pythonic way to prevent/correct that kind of outputs? Reply Posts: 3,298 Threads: 45 Joined: Jan 2018 Reputation: Aug-27-2020, 12:10 PM (This post was last modified: Aug-27-2020, 12:10 PM by Gribouillis.) Normally, Python's floats adhere internally to the IEEE 754 specification for floating point arithmetics which uses a signed zero. It means that the numbers 0.0 and -0.0 differ internally by one bit, the sign bit. As python values, they compare equal though, that is to say `0.0 == -0.0` returns True. If you want to avoid the negative zero you could do `root = (-b + discr**0.5) / (2 * a) or 0.0`for example. Observe that the two numbers are also considered equal in dictionaries, for example ```>>> {0.0: 'foo', -0.0: 'bar'} {0.0: 'bar'}``` Reply akar Unladen Swallow Posts: 3 Threads: 2 Joined: Aug 2020 Reputation: Aug-27-2020, 12:15 PM Ok, I did not know about the IEEE 754 standard and signed zeros. Thanks for your answer. Now I know I'll have to be cautious about that. "Problem" solved! Reply

 Possibly Related Threads… Thread Author Replies Views Last Post Solve simple equation in Python kmll 4 1,164 Nov-01-2020, 04:34 PM Last Post: deanhystad Python scipy odeint: solving with solution-dependent functions etienne 0 1,095 Jun-05-2020, 01:29 PM Last Post: etienne Looking for solution in Python ankitasharma111 1 995 Oct-01-2019, 12:35 PM Last Post: ichabod801 Python modeling a math solution Masterwoot 1 1,201 Mar-01-2019, 08:50 AM Last Post: buran Asking for help in solving a single variable nonlinear equation using Python ! NDP 0 1,191 Feb-15-2019, 12:03 PM Last Post: NDP How can I put an np.arange in equation's solution? pianistseb 3 1,386 Dec-22-2018, 02:50 AM Last Post: SheeppOSU How do I code this equation in python (factor ceiling(2^127-1)) Pleiades 5 2,565 Apr-23-2018, 03:01 AM Last Post: Skaperen

Forum Jump:

### User Panel Messages

##### Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020