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

1 投票
1 回答
3983 浏览
提问于 2025-04-18 09:53

我有一个线性方程和一个二次方程的系统,可以用 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

从图中可以看出,这两个函数有交点,所以它们之间是有解的。

我该如何自动计算出这个解(交点),同时又能保持大部分函数定义不变呢?

1 个回答

4

其实可以用 scipy.optimize.fsolve 来解决这个问题,只需要注意,原作者提到的函数需要用 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

参考资料:

撰写回答