求解非线性方程式numpy。

时间:2018-08-19 18:28:36

标签: python arrays numpy scipy nonlinear-optimization

编辑: 一切都很好:)

 This is a code which works with small values of t=20 and TR=([[30,20,12,23..],[...]]) but when I put higher values it is shown "Expect x to be a 1-D sorted array_like.". Do you know how to solve this problem??  

import matplotlib.pylab as plt
from scipy.special import erfc
from scipy import  sqrt
from scipy import  exp
import numpy as np
from scipy.interpolate import interp1d




# The function to inverse:
t = 100
alfa = 1.1*10**(-7)
k = 0.18
T1 = 20
Tpow = 180

def F(h):
    p = erfc(h*sqrt(alfa*t)/k)
    return T1 + (Tpow-T1)*(1-exp((h**2*alfa*t)/k**2)*(p))

# Interpolation 
h_eval = np.linspace(-80, 500, 200)   # critical step: define the discretization grid
F_inverse = interp1d( F(h_eval), h_eval, kind='cubic', bounds_error=True )


# Some random data:
TR = np.array([[130, 100, 130, 130, 130],
       [ 90, 101, 100, 120,  90],
       [130, 130, 100, 100, 130],
       [120, 101, 120,  90, 110],
       [110, 130, 130, 110, 130]])

# Compute the array h for a given array TR
h = F_inverse(TR)
print(h)

# Graph to verify the interpolation 
plt.plot(h_eval, F(h_eval), '.-', label='discretized F(h)');
plt.plot(h.ravel(), TR.ravel(), 'or', label='interpolated values')
plt.xlabel('h'); plt.ylabel('F(h) or TR'); plt.legend();


有谁知道如何在numpy中求解非线性隐式方程。 我的方程式中包含数组TR和其他值。

我需要解决它-结果会收到一个形状相同的新数组

1 个答案:

答案 0 :(得分:1)

这是一种使用1D插值计算F(h)函数的逆函数的解决方案。因为使用了非standard root finding method,所以无法控制错误,必须谨慎选择离散网格。但是,插值逆函数可以直接在数组上计算。

注意:F的定义已被修改,现在的问题是Solve h for F(h) = TR

import numpy as np
from scipy.interpolate import interp1d
import matplotlib.pylab as plt

# The function to inverse:
t = 10
alfa = 1.1*10**(-7)
k = 0.18
T1 = 20
Tpow = 100

def F(h):
    A = np.exp(h**2*alfa*t/k**2)
    B = h**3*2/(3*np.sqrt(3))*(alfa*t)**(3/2)/k**3
    return -(Tpow-T1)*( 1 - A + B )

# Interpolation 
h_eval = np.linspace(40, 100, 50)   # critical step: define the discretization grid
F_inverse = interp1d( F(h_eval), h_eval, kind='cubic', bounds_error=True )


# Some random data:
TR = np.array([[13, 10, 13, 13, 13],
       [ 9, 11, 10, 12,  9],
       [13, 13, 10, 10, 13],
       [12, 11, 12,  9, 11],
       [11, 13, 13, 11, 13]])

# Compute the array h for a given array TR
h = F_inverse(TR)
print(h)

# Graph to verify the interpolation 
plt.plot(h_eval, F(h_eval), '.-', label='discretized F(h)');
plt.plot(h.ravel(), TR.ravel(), 'or', label='interpolated values')
plt.xlabel('h'); plt.ylabel('F(h) or TR'); plt.legend();

使用其他功能,更改了以下几行:

from scipy.special import erf
def F(h):
    return (Tpow-T1)*(1-np.exp((h**2*alfa*t)/k**2)*(1.0-erf(h*np.sqrt(alfa*t)/k)))

# Interpolation 
h_eval = np.linspace(15, 35, 50)   # the range is changed