【发布时间】:2015-03-25 20:13:23
【问题描述】:
我在*上找到了以下代码sn-p,但我遇到了stdev变成NaN的问题。任何想法如何解决这个问题?
public static void AddBollingerBands(ref SortedList<DateTime, Dictionary<string, double>> data, int period, int factor)
{
double total_average = 0;
double total_squares = 0;
for (int i = 0; i < data.Count(); i++)
{
total_average += data.Values[i]["close"];
total_squares += Math.Pow(data.Values[i]["close"], 2);
if (i >= period - 1)
{
double total_bollinger = 0;
double average = total_average / period;
double stdev = Math.Sqrt((total_squares - Math.Pow(total_average,2)/period) / period);
data.Values[i]["bollinger_average"] = average;
data.Values[i]["bollinger_top"] = average + factor * stdev;
data.Values[i]["bollinger_bottom"] = average - factor * stdev;
total_average -= data.Values[i - period + 1]["close"];
total_squares -= Math.Pow(data.Values[i - period + 1]["close"], 2);
}
}
}
【问题讨论】:
-
你确定
period永远不会是0吗?自己解决这个问题。它在你的循环中什么时候变成 NaN(即在多少次迭代之后)。是正无穷还是负无穷?在var stdev = ...行的计算中使用的任何其他值是否在此时变为 NaN? -
在我看来,您需要的不是这个特定问题的答案,而是花一些时间学习调试代码。检测代码并找出导致问题的操作?缩小问题范围?
-
谢谢,但经过几次迭代后,参数具有以下值:total_squares = 18.42483;总平均 = 19.19628;周期 = 20;以 NaN 结束
-
使用这些数字:
total_squares - Math.Pow(total_average,2)/period是-0.00002829192。 IE。你取平方根的负数。这将导致 NaN。 -
顺便说一句 - 参数列表中的
ref似乎是不必要的。
标签: c# standard-deviation