gpt4 book ai didi

c# - 在 F# 中重写 C# 代码

转载 作者:太空狗 更新时间:2023-10-29 22:13:15 24 4
gpt4 key购买 nike

只是弄乱了 F#,我试图基于这个 C# 版本(从 C++ wiki 条目复制)创建一个基本的拉格朗日插值函数:

    double Lagrange(double[] pos, double[] val, double desiredPos)
{
double retVal = 0;

for (int i = 0; i < val.Length; ++i)
{
double weight = 1;

for (int j = 0; j < val.Length; ++j)
{
// The i-th term has to be skipped
if (j != i)
{
weight *= (desiredPos - pos[j]) / (pos[i] - pos[j]);
}
}

retVal += weight * val[i];
}

return retVal;
}

利用我对 F# 和函数式编程的有限知识,我能想到的最好的办法是:

let rec GetWeight desiredPos i j (pos : float[]) weight = 
match i with
| i when j = pos.Length -> weight
| i when i = j -> GetWeight desiredPos i (j+1) pos weight
| i -> GetWeight desiredPos i (j+1) pos (weight * (desiredPos - pos.[j])/(pos.[i] - pos.[j]) )

let rec Lagrange (pos : float[]) (vals : float[]) desiredPos result counter =
match counter with
| counter when counter = pos.Length -> result
| counter -> Lagrange pos vals desiredPos (result + (GetWeight desiredPos counter 0 pos 1.0)* vals.[counter]) (counter+1)

有人可以提供基于相同 C# 代码的更好/更整洁的 F# 版本吗?

最佳答案

折叠序列是用累加器代替循环的常用方法。

let Lagrange(pos:_[], v:_[], desiredPos) =
seq {0 .. v.Length-1}
|> Seq.fold (fun retVal i ->
seq {for j in 0 .. pos.Length-1 do if i <> j then yield j}
|> Seq.fold (fun w j -> w * (desiredPos - pos.[j]) / (pos.[i] - pos.[j])) 1.0
|> (fun weight -> weight * v.[i] + retVal)) 0.0

关于c# - 在 F# 中重写 C# 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1601120/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com