James Jameson
James Jameson

Reputation: 57

How do I translate a math formula to python code?

I need to translate this formula into python:

x = b + (sqrt((b^2)-1)) / 2a

Can somebody please help me?

Upvotes: 1

Views: 1788

Answers (3)

CypherX
CypherX

Reputation: 7353

This should work as well. No need to import any library. Assuming a != 0.

When b >= 1:

x = b + (((b ** 2) - 1 ) ** 0.5) / (2 * a)

NOTE: You should ideally have two roots for sqrt(b^2 - 1). Your function should return both values. Now, I am guessing that, under certain prior knowledge you have decided to only keep the positive root.

When b == 0, you get two roots. Note that sqrt(-1) = j or -j (complex roots).

x = (+1j) / (2 * a) # positive root
# OR
x = (-1j) / (2 * a) # negative root

More generally, when b**2 < 1, you get two complex roots.

x = b + (k*1j) ((1 - (b ** 2)) ** 0.5) / (2 * a) 
# positive root: k = +1
# OR
# negative root: k = -1

Upvotes: 0

leopardxpreload
leopardxpreload

Reputation: 768

Mathematically correct this solution is

import math
import cmath
def quadratic(a, b, c):
    if b == 0:
        f = (cmath.sqrt(b ** 2 - 1 )) / (2 * a)
    else:
        f = (math.sqrt(b ** 2 - 1 )) / (2 * a)
    return b + f, b -f

print(quadratic(1, 2, 3))

This will give you the two roots.

You can access the roots by indexing:

my_roots = quadratic(1, 2, 3)
x_1 = my_roots[0]
x_2 = my_roots[1]

By using a Python function , you can re-use this code.

Upvotes: 2

Meera
Meera

Reputation: 88

import math
x = b + (math.sqrt((b ** 2) - 1 )) / (2 * a)

Upvotes: 2

Related Questions