解决使用Python和Sympy解决涉及三角函数的非线性方程组问题

huangapple go评论61阅读模式
英文:

Problems solving nonlinear systems of equations involving trig functions in Python using Sympy

问题

以下是翻译好的内容,去掉了代码部分:

"I'm trying to create a program that solves the solutions for an equation of a circle:

This is the code I wrote for it using Sympy. It works for functions like x^2, but I always encounter an error when using tan(x) or sin(x)

Graphical solutions show that a solution definitely exists."

英文:

I'm trying to create a program that solves the solutions for an equation of a circle:

解决使用Python和Sympy解决涉及三角函数的非线性方程组问题

This is the code I wrote for it using Sympy. It works for functions like x^2, but I always encounter an error when using tan(x) or sin(x)

import sympy as sym

x = sym.symbols('x')
y = sym.symbols('y')
f = sym.Eq(sym.sqrt(9-x**2), y)
g = sym.Eq(sym.tan(x), y)
print(sym.solve((f, g)(x, y)))

Graphical solutions show that a solution definitely exists.

答案1

得分: 3

"解决方案的图表显示,这并不意味着可以通过分析方法计算解决方案。solve 用于获得分析解决方案。我们可以使用 nsolve 来计算数值解,但我们需要找到合适的初始条件,因此图表非常重要。

from sympy import *
var("x, y")
eq1 = Eq(y, sqrt(9 - x**2))
eq2 = Eq(y, tan(x))
plot(eq1.rhs, eq2.rhs, (x, -pi, pi), ylim=(-5, 5))

图表显示在区间[-pi, pi]中有3个解。阅读 help(nsolve) 以熟悉其语法。要找到解决方案,我们需要尝试不同的初始猜测值:

s1 = nsolve([eq1, eq2], [x, y], [-2, 2])
s2 = nsolve([eq1, eq2], [x, y], [1, 2])
s3 = nsolve([eq1, eq2], [x, y], [-2.9, 0.5])
print(s1)
print(s2)
print(s3)
# 输出
# Matrix([[-1.98982600933056], [2.24512637786642]])
# Matrix([[1.22089272895276], [2.74033226897584]])
# Matrix([[-2.99643622736316], [0.146184593393441]])

您可以通过图形验证这些解决方案的正确性。"

英文:

Just because plots show a solution, it doesn't mean that the solution can be computed analytically. solve is used to get an analytical solution. We can use nsolve to compute a numerical solution, but we are going to find suitable initial conditions, hence a plot is more than welcome.

from sympy import *
var("x, y")
eq1 = Eq(y, sqrt(9 - x**2))
eq2 = Eq(y, tan(x))
plot(eq1.rhs, eq2.rhs, (x, -pi, pi), ylim=(-5, 5))

解决使用Python和Sympy解决涉及三角函数的非线性方程组问题

The plot shows that there are 3 solutions in the interval [-pi, pi]. Read help(nsolve) to get acquainted with its syntax. To find the solutions we will have to play with initial guesses:

s1 = nsolve([eq1, eq2], [x, y], [-2, 2])
s2 = nsolve([eq1, eq2], [x, y], [1, 2])
s3 = nsolve([eq1, eq2], [x, y], [-2.9, 0.5])
print(s1)
print(s2)
print(s3)
# out
# Matrix([[-1.98982600933056], [2.24512637786642]])
# Matrix([[1.22089272895276], [2.74033226897584]])
# Matrix([[-2.99643622736316], [0.146184593393441]])

You can verify graphically that the solutions are correct.

huangapple
  • 本文由 发表于 2023年4月4日 12:51:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75925615.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定