我有一个类似这样的数据文件:
0 0
0.1 0.1
0.2 0.2
0.3 0.3
0.4 0.31
0.5 0.32
0.6 0.35
我想找到与斜坡相交的值。 到目前为止,我的代码看起来像这样:
from numpy import *
from pylab import *
data = loadtxt('test.dat')
strain = data[:,0]
stress = data[:,1]
E = 1
y = [0, 0.5]
x = 0.2, ((y[1] - y[0])/E+0.2)
figure(num=None, figsize=(10, 6), dpi=100, facecolor='w', edgecolor='k')
plot(strain, stress)
plot(x, y)
show()
答案 0 :(得分:3)
您可以使用scipy中的interp1d
函数在每组点之间创建线性插值。 interp1d
获取x和y值并返回一个取x值并返回相应y值的函数。一旦你有压力和y的函数,你需要弄清楚那些相交的位置。有效地做到这一点的一种方法是使用像bisection方法那样找到零。
这里是代码:import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d
from scipy.optimize import bisect
data = '''0 0
0.1 0.1
0.2 0.2
0.3 0.3
0.4 0.31
0.5 0.32
0.6 0.35'''
data = [line.split() for line in data.split('\n')]
data = np.array(data, dtype = 'float')
strain = data[:,0]
stress = data[:,1]
E = 1
y = [0, 0.5]
x = 0.2, ((y[1] - y[0])/E+0.2)
#use interp1d to get interpolated points
y = interp1d(x, y)
stress = interp1d(strain, stress)
#set starting points
x1 = max(x[0], strain[0])
x2 = min(x[-1], strain[-1])
max_err = .01
#create function
f = lambda x : stress(x) - y(x)
#find x1 where f(x1) = 0
x1 = bisect(f, x1, x2, xtol = .001)
y1 = stress(x1)
plt.figure(num=None, figsize=(10, 6), dpi=100, facecolor='w', edgecolor='k')
plt.plot(strain, stress(strain))
plt.plot(x, y(x))
plt.scatter(x1, y1)
plt.show()