函数类型的曲线拟合:y=10^((ax)/10*b)

2024-05-15 06:15:35 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是根据传感器(列x)的值计算的距离(列y)。你知道吗

你知道吗测试.txt-内容

x   y   
----------


-51.61  ,1.5
-51.61  ,1.5
-51.7   ,1.53
-51.91  ,1.55
-52.28  ,1.62
-52.35  ,1.63
-52.49  ,1.66
-52.78  ,1.71
-52.84  ,1.73
-52.90  ,1.74
-53.21  ,1.8
-53.43  ,1.85
-53.55  ,1.87
-53.71  ,1.91
-53.99  ,1.97
-54.13  ,2
-54.26  ,2.03
-54.37  ,2.06
-54.46  ,2.08
-54.59  ,2.11
-54.89  ,2.19
-54.94  ,2.2
-55.05  ,2.23
-55.11  ,2.24
-55.17  ,2.26

我想通过曲线拟合找到ab中数据的常数test.txt,基于此函数:

Function y = 10^((a-x)/10*b) 

我使用以下代码:

import math

from numpy import genfromtxt  
from scipy.optimize import curve_fit 

inData = genfromtxt('test.txt',delimiter=',')

rssi_data = inData[:,0]
dist_data= inData[:,1]

print rssi_data
print dist_data

def func(x, a,b):
    exp_val = (x-a)/(10.0*b) 
    return math.pow(10,exp_val)

coeffs, matcov = curve_fit(func,rssi_data,dist_data)

print(coeffs)
print(matcov)

代码未成功执行。另外,我不确定是否将正确的参数传递给了curve_fit()。你知道吗


Tags: 代码fromtestimporttxtdatadistmath
2条回答

我对前面的答案投了赞成票,因为它是编程问题的正确答案。但仔细看,你不需要做幂律拟合:

y = 10^((a-x)/10*b) <=> log10(y) = log10(10^((a-x)/10*b)) 
<=> log10(y) = (a-x)/10*b

使用新变量:

z = log10(y), c = a/10*b and d = -1/10*b 

你现在必须适应以下条件:

z = dx + c

这是一条直线。好吧,你只需要将上面的变换应用到表中的2个点(x,y)=>;(x,log10(y)),然后拟合一条直线,得到c,d,从而得到a,b

我写这篇文章是因为你可能要做很多次,这比安装电源简单得多功能。它当你计划你的实验时也会有后果。如果你知道这是正确的拟合函数,你基本上只需要2点就可以得到一般的行为。你知道吗

我希望这有帮助。干杯!你知道吗

该函数需要处理numpy数组,但目前无法处理,因为math.pow需要一个标量值。如果我执行你的代码,我会得到以下异常:

TypeError: only length-1 arrays can be converted to Python scalars

如果将函数更改为:

def func(x, a, b):
    return 10 ** ((a - x) / (10 * b))  # ** is the power operator

它应该毫无例外地发挥作用:

>>> print(coeffs)
[-48.07485338   2.00667587]
>>> print(matcov)
[[  3.59154631e-04   1.21357926e-04]
 [  1.21357926e-04   4.25732516e-05]]

完整代码如下:

def func(x, a, b):
    return 10 ** ((a - x) / (10 * b))

coeffs, matcov = curve_fit(func, rssi_data, dist_data)

# And some plotting for visualization

import matplotlib.pyplot as plt
%matplotlib notebook  # only works in IPython notebooks

plt.figure()
plt.scatter(rssi_data, dist_data, label='measured')
x = np.linspace(rssi_data.min(), rssi_data.max(), 1000)
plt.plot(x, func(x, coeffs[0], coeffs[1]), label='fitted')
plt.legend()

enter image description here

相关问题 更多 >

    热门问题