gpt4 book ai didi

python - 在 numpy/matplotlib 中以图形和数字方式求解线性二次方程组?

转载 作者:太空宇宙 更新时间:2023-11-04 10:34:33 25 4
gpt4 key购买 nike

我有一个线性方程组和一个二次方程组,我可以用 numpyscipy 建立它们,这样我就可以获得图形解决方案。考虑示例代码:

#!/usr/bin/env python
# Python 2.7.1+

import numpy as np #
import matplotlib.pyplot as plt #

# d is a constant;
d=3
# h is variable; depends on x, which is also variable

# linear function:
# condition for h: d-2x=8h; returns h
def hcond(x):
return (d-2*x)/8.0

# quadratic function:
# condition for h: h^2+x^2=d*x ; returns h
def hquad(x):
return np.sqrt(d*x-x**2)

# x indices data
xi = np.arange(0,3,0.01)

# function values in respect to x indices data
hc = hcond(xi)
hq = hquad(xi)

fig = plt.figure()
sp = fig.add_subplot(111)

myplot = sp.plot(xi,hc)
myplot2 = sp.plot(xi,hq)

plt.show()

该代码生成此图:

test02.png

很明显,这两个函数是相交的,因此有一个解决方案。

我怎样才能自动解决解决方案(交点),同时保持大部分函数定义不变?

最佳答案

事实证明可以使用 scipy.optimize.fsolve 来解决这个问题,只需要注意 OP 中的函数定义在 y=f(x) 格式;而 fsolve 将需要它们采用 f(x)-y=0 格式。这是固定代码:

#!/usr/bin/env python
# Python 2.7.1+

import numpy as np #
import matplotlib.pyplot as plt #
import scipy
import scipy.optimize

# d is a constant;
d=3
# h is variable; depends on x, which is also variable

# linear function:
# condition for h: d-2x=8h; returns h
def hcond(x):
return (d-2*x)/8.0

# quadratic function:
# condition for h: h^2+x^2=d*x ; returns h
def hquad(x):
return np.sqrt(d*x-x**2)

# for optimize.fsolve;
# note, here the functions must be equal to 0;
# we defined h=(d-2x)/8 and h=sqrt(d*x-x^2);
# now we just rewrite in form (d-2x)/16-h=0 and sqrt(d*x-x^2)-h=0;
# thus, below x[0] is (guess for) x, and x[1] is (guess for) h!
def twofuncs(x):
y = [ hcond(x[0])-x[1], hquad(x[0])-x[1] ]
return y

# x indices data
xi = np.arange(0,3,0.01)

# function values in respect to x indices data
hc = hcond(xi)
hq = hquad(xi)

fig = plt.figure()
sp = fig.add_subplot(111)

myplot = sp.plot(xi,hc)
myplot2 = sp.plot(xi,hq)


# start from x=0 as guess for both functions
xsolv = scipy.optimize.fsolve(twofuncs, [0, 0])
print(xsolv)
print("xsolv: {0}\n".format(xsolv))

# plot solution with red marker 'o'
myplot3 = sp.plot(xsolv[0],xsolv[1],'ro')


plt.show()

exit

...结果是:

xsolv: [ 0.04478625  0.36380344]

...或者,在绘图图像上:

test02a.png

引用:

关于python - 在 numpy/matplotlib 中以图形和数字方式求解线性二次方程组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24234892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com