我正在尝试将 fsolve 应用于数组:
from __future__ import division
from math import fsum
from numpy import *
from scipy.optimize import fsolve
from scipy.constants import pi
nu = 0.05
cn = [0]
cn.extend([pi*n - pi/4 for n in range(1, 5 +1)])
b = linspace(200, 600, 400)
a = fsolve(lambda a: 1/b + fsum([1/(b+cn[i]) for i in range(1, 5 +1)]) - nu*(sqrt(a) - 1)**2, 3)
默认情况下不允许:
TypeError: only length-1 arrays can be converted to Python scalars
有没有办法可以将 fsolve 应用于数组?
编辑:
#!/usr/bin/env python
from __future__ import division
import numpy as np
from scipy.optimize import fsolve
nu = np.float64(0.05)
cn = np.pi * np.arange(6) - np.pi / 4.
cn[0] = 0.
b = np.linspace(200, 600, 400)
cn.shape = (6,1)
cn_grid = np.repeat(cn, b.size, axis=1)
K = np.sum(1/(b + cn_grid), axis=0)
f = lambda a: K - nu*(np.sqrt(a) - 1)**2
a0 = 3. * np.ones(K.shape)
a = fsolve(f, a0)
print a
解决它。