Home > Blockchain >  Three nonlinear equations with three unknowns - how can be solved with f.solve?
Three nonlinear equations with three unknowns - how can be solved with f.solve?

Time:11-10

I am new to Python. I am sharing a code snippet which is a part of a code to read data from a file and make the needed calculations. I have 3 nonlinear eqs with 3 unknowns. I wrote the following code to solve it, but the code gives me an error of:

File "<ipython-input-46-bc67ad1b6153>", line 4
    eq2 = (y/(1-y) - (5/(8*np.pi * np.cos(z))) * (1 - (np.cot(z)))
    ^
SyntaxError: invalid syntax

I do not think the syntax is wrong, but I am not sure if this kind of solution works in my case. Also, my variable "x" should be in the rage between 1/4 and 1/3

My code:

    import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
from scipy.optimize import fsolve
def equations(vars):
    x, y, z = vars
    eq1 = (x/(1-x) - (5/(8*np.pi*np.sin(z)**2) * (1   4*(np.tan(z))
    eq2 = (y/(1-y) - (5/(8*np.pi * np.cos(z))) * (1 - (np.cot(z)))
    eq3 = np.tan(z) - ((1-x) / 3 * (1 y))
    return [eq1, eq2, eq3]

x, y,z =  fsolve(equations, (1, 1, 1))

print(x, y, z)

CodePudding user response:

I encountered some errors in your code:

  1. there's no np.cot function you maybe want to use 1/np.tan(z) in equation 3.
  2. you forgot some parentheses (eq1 and eq2) so it will never work (I might put some but i'm just guessing. you might to correct that part
  3. your initial guess (1,1,1) causes a singularity in eq1 and eq2

so here a proposal (check parentheses)

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import math
from scipy.optimize import fsolve
def equations(vars):
    x, y, z = vars
    eq1 = (x/(1-x)) - (5/(8*np.pi*np.sin(z)**2)) * (1   4*(np.tan(z)))
    eq2 = (y/(1-y)) - (5/(8*np.pi * np.cos(z))) * (1 - (1/np.tan(z)))
    eq3 = np.tan(z) - ((1-x) / 3 * (1 y))
    return [eq1, eq2, eq3]

x, y,z =  fsolve(equations, (2, 2, 2))

print(x, y, z)
#prints: 1.4489745262423956 26.230116359918174 1.8114278561902486

CodePudding user response:

You have wrong number of parenthesis in several lines of code. Also there is no np.cot(), use 1 / np.tan() instead. Fixed working code below:

Try it online!

import numpy as np
import math
from scipy.optimize import fsolve
def equations(vars):
    x, y, z = vars
    eq1 = (x / (1 - x) - (5 / (8 * np.pi * np.sin(z) ** 2) * (1   4 * np.tan(z))))
    eq2 = (y / (1 - y) - (5 / (8 * np.pi * np.cos(z))) * (1 - (1 / np.tan(z))))
    eq3 = np.tan(z) - ((1-x) / 3 * (1 y))
    return [eq1, eq2, eq3]

x, y,z =  fsolve(equations, (1, 1, 1))

print(x, y, z)

Output:

1.0 1.0 1.0
  • Related