我已经在Python 3中创建了一个程序,它以y = a * b^x
的形式估计指数函数给定多个测量点。
我不是第一个这样做的人,因为有很多程序可以做同样的事情,但是如果他们做得比我好(他们是可能会这样做。
如果您想阅读(不必要),请输入以下代码:
from math import log, exp
# The function will first be estimated in the form y = a*e^(kx)
# and then converted to the form y = a*b^x where b = e^x
xList = [] # Contains all the x-values
yList = [] # Contains all the corresponding y-values
kList = [] # Contains all the k-values
aList = [] # Contains all the a-values
n = int(input("How many points will you input?: "))
for i in range(n):
x, y = map(float, input("Please enter an x-value and its corresponding y-value:\n").split())
xList.append(x)
yList.append(y)
for i in range(n):
for j in range(i+1, n):
# The k-value is calculated as k = ln(y1/y2)/(x1-x2)
kList.append(log(yList[i]/yList[j]) / (xList[i]-xList[j]))
# Because the points given are supposed to be from physical experiments
# the k-value will not be constant throughout all measurements.
# To go around this I take the average of all k-values
k = sum(kList)/len(kList)
for i in range(n):
# The a-value is calculated as a = y1/e^(kx1)
aList.append(yList[i]/exp(k*xList[i]))
# Taking the average for the same reason as the k-value
a = sum(aList)/len(aList)
# Calculating the b-value
b = exp(k)
fin = "y = " + str(a) + " * " + str(b) + "^x"
print("\n")
print("The estimated function is:\n{}".format(fin))
抱歉我的骇人听闻的代码
对于那些不想阅读我的代码的人,请按以下步骤操作:
y = a * b^x
y = a * e^(k*x)
{x1, x2, x3, ..., xn}
及其对应的y值{y1, y2, y3, ..., yn}
,我们估计k值(xi, yi)
和(xj, yj)
的k值计算为k = ln(y1/y2) / (x1-x2)
(xi, yi)
的a值计算为a = yi / e^(k*xi)
b = e^k
我可以做些什么来获得更好更快的估算?