Search code examples
pythonsympynonlinear-optimizationequation-solvingnonlinear-functions

How to solve nonlinear equations using a for loop in python?


I am trying to solve for non linear equations in python. I have tried using the solver of the Sympy but it doesn't seem to work in a for loop statement. I am tyring to solve for the variable x over a range of inputs [N].

I have attached my code below

import numpy as np
import matplotlib.pyplot as plt
from sympy import *

f_curve_coefficients = [-7.14285714e-02, 1.96333333e+01, 6.85130952e+03]
S = [0.2122, 0, 0]

a2 = f_curve_coefficients[0]
a1 = f_curve_coefficients[1]
a0 = f_curve_coefficients[2]

s2 = S[0]
s1 = S[1]
s0 = S[2]

answer=[]
x = symbols('x')
for N in range(0,2500,5):
    solve([a2*x**2+a1*N*x+a0*N**2-s2*x**2-s1*x-s0-0])
    answer.append(x)
    
print(answer)

There could be more efficient ways of solving this problem than using sympy * any help will be much appreicated.

Note I am still new to python, after transisitioning from Matlab. I could easliy solve this problem in Matlab and could attach the code, but I am battiling with this in Python


Solution

  • According to this documentation, the output of solve is the solution. Nothing is assigned to x, that's still just the symbol.

    x = symbols('x')
    for N in range(0,2500,5):
        result = solve(a2*x**2+a1*N*x+a0*N**2-s2*x**2-s1*x-s0-0)
        answer.append(result)