像excel输出一样在Python中生成非线性方程



下面是一些示例数据:

免费模式:0.5,0.3333,0.1666,0.0466,0.0466,0.1,0.1666,0.3333、0.5
分钟:0、60、120、180、240、300、360、420、480

我想用这些数据来建立一个非线性方程,其中分钟是x,免费增值是y。

作为参考方程,我使用相同的数据在excel中创建了分钟和免费增值的非线性方程,excel使方程看起来像这样:

y = -0.000000000000001561203414339570x6 + 0.000000000002445980336850290000x5 - 0.000000001484771616406030000000x4 + 0.000000431626331238999000000000x3 - 0.000050863545408175200000000000x2 - 0.000887445386510421000000000000x + 0.49912561449686200000000000000000

我想使用python(最好是pandas)来构建一个非线性方程,该方程像上面的excel一样打印我在表中的数据。

您可以使用Numpy库中的polyfit来完成此操作。格式化等式只需几行代码。您可以更改循环以匹配您喜欢的格式。

import numpy as np
minutes = [0, 60, 120, 180, 240, 300, 360, 420, 480] 
freemium = [0.5, 0.3333, 0.1666, 0.0466, 0.0466, 0.1, 0.1666, 0.3333, 0.5]
degree = 6
coefficients = np.polyfit(minutes, freemium, degree)
equation = "y = "
for i, coeff in enumerate(coefficients):
power = degree - i
if power < degree:
equation += " + "
equation += str(coeff)
if power == 1:
equation += " x"
elif power > 1:
equation += f" x^{power}"
print(equation)

打印

y = -1.562261850327855e-15 x^6 + 2.4477517938168308e-12 x^5 + -1.4858670992931515e-09 x^4 + 4.319296328671704e-07 x^3 + -5.089791979625905e-05 x^2 + -0.0008867371406366774 x + 0.49912484848483274

最新更新