所以我得求出这个函数的系数。
https://mathworld.wolfram.com/LeastSquaresFittingPowerLaw.html
我想我输入变量“a”的方程是正确的,答案应该在8左右。但它一直给我一个2左右的答案。我在过程中哪里出错了吗?
> import matplotlib.pyplot as mp
> import math
>
> # (x, y) data values
> xList = [1, 2, 3, 4, 5, 6]
> yList = [8, 11, 19, 20, 18, 22]
> x = xList.copy()
> y = yList.copy()
> print (x)
> print (y)
>
> Power Fit variables
> n = len(x)
> sumLog_x = 0
> sumLog_y = 0
> sumLog_xx = 0
> sumLog_xy = 0
> b = 0; b_Num = 0; b_Denom = 0
> a = 0; a_Num = 0; a_Denom = 0
>
> for i in range(n) :
> sumLog_x += math.log(x[i])
> sumLog_y += math.log(y[i])
> sumLog_xx += math.log(x[i]) * math.log(x[i])
> sumLog_xy += math.log(x[i]) * math.log(y[i])
>
> compute the exponent b
> b_Num = n * sumLog_xy - sumLog_x * sumLog_y
> b_Denom = n * sumLog_xx - sumLog_x * sumLog_x
> b = b_Num / b_Denom
>
>
> a_Num = (sumLog_y) - (sumLog_x * b)
> a_Denom = n
> a = a_Num / a_Denom
>
> print ("modeling: y = a * x^b")
> print ("exponent b = ", format(b, "0.6f"))
> print ("exponent a = ", format(a, "0.6f"))
我的输出如下
> [1, 2, 3, 4, 5, 6]
> [8, 11, 19, 20, 18, 22]
> modeling: y = a * x^b
> exponent b = 0.573009
> exponent a = 2.104825
为什么“a”是2.1?
1条答案
按热度按时间lokaqttq1#
因为你忘记了正确地计算
A
为np.exp(a)。下面是最终的测试代码:对我来说,最终的解决方案似乎是正确的,最小二乘拟合与数据匹配。