找到给定多个点的指数函数

时间:2017-12-16 20:50:21

标签: python python-3.x algorithm

我已经在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))

抱歉我的骇人听闻的代码

对于那些不想阅读我的代码的人,请按以下步骤操作:

  1. 我们想要找到一个函数y = a * b^x
  2. 我们将首先以y = a * e^(k*x)
  3. 的形式估算函数
  4. 鉴于x值{x1, x2, x3, ..., xn}及其对应的y值{y1, y2, y3, ..., yn},我们估计k值
  5. (xi, yi)(xj, yj)的k值计算为k = ln(y1/y2) / (x1-x2)
  6. 计算点(xi,yi)(xj,yj)的所有k值,使得i <1。 j并将最终的k值设为平均值
  7. 鉴于k值,我们现在可以将点(xi, yi)的a值计算为a = yi / e^(k*xi)
  8. 计算所有点的a值并取平均值
  9. 最后将b值计算为b = e^k
  10. 我可以做些什么来获得更好更快的估算?

0 个答案:

没有答案