Python function: How to calculate x in a cubic equation using python

70 Views Asked by At

How to find the value of x from the equation calculate_density(x)?

I have the following Python function:

a = 5108.30
b = 3967550
c = -281375000
pressure = 100
def calculate_density(x):
    density = (a * x + b * x**2 + c * x**3) * pressure
    return density

The function takes in a value for x and returns the density value. I want to find the value of x from the equation when the density is given.

Is there a way to do this in Python?

x_solution = fsolve(equation, x_initial_guess, args=(a, b, c, density, pressure)) 

but the results are not giving me optimal solution

1

There are 1 best solutions below

0
not_speshal On

Since your equation is a cubic polynomial, you could have 3 values for x. To find the roots, you can use numpy:

import numpy as np

def fsolve(a, b, c, density, pressure):
    return np.roots([c,b,a,-density/pressure])