#[
线性拟合的例子
参考
https://zhuanlan.zhihu.com/p/80969579使用
https://nim-lang.org/ 实现
]#
import math
import lenientops
import strformat
proc mean(x: seq[float|float32|int]): float32 =
return x.sum/x.len
proc `*`[A: float|float32|int, B: float|float32|int](x: seq[A], y: seq[B]): seq[float32] =
for i in 0 ..< len(x):
result.add float32(x[i] * y[i])
return result
proc `-`[A: float|float32|int, B: float|float32|int](x: seq[A], y: seq[B]): seq[float32] =
for i in 0 ..< len(x):
result.add float32(x[i] - y[i])
return result
proc `*`(n:float|int, y: seq[float|float32|int]): seq[float32] =
for i in 0 ..< len(y):
result.add float32(n * y[i])
return result
proc `-`(x: seq[float|float32|int], n:float|float32|int): seq[float32] =
for i in 0 ..< len(x):
result.add float32(x[i] - n)
return result
var
x = @[427, 459, 611, 593, 588]
y = @[-49.18, -22.21, 55.96, 117.37, 119.74]
var
mean_x = mean(x)
w = (y*(x - mean_x)).sum()/((x*x).sum()-x.sum()*x.sum()/len(x))
b = (y-w*x).sum()/len(x)
echo fmt"线性拟合得到的方程为y = {w:.2f}*x + {b:.2f}"
echo fmt"煤价为{-b/w:.2f}时,净利润为0"
【 在 chh811 (chh) 的大作中提到: 】
: 类别 2015年 2016年 2017年 2018年 2019年
: 煤价 427 459 611 593 588
: 净利润 -49.18 -22.21 55.96 117.37 119.74
: ...................
--
FROM 117.140.170.*