Performing a calculation but only getting NaN as a result

public double calculateStdErrorEst()
{
    double see = 0;
    double residualSquare = 0;
    CultureInfo culture = new CultureInfo("en-US");
    List<double> residualTotal = new List<double>();

    try
    {
        for (int i = 0; i < stockPctReturns.Count; i++)
        {
            // square root of all sums of predicted - actual or market - stock
            residualSquare = Math.Sqrt(Convert.ToDouble((marketPctReturns.ElementAt(i) - stockPctReturns.ElementAt(i)), culture));
            residualTotal.Add(Math.Round(residualSquare, 2, MidpointRounding.AwayFromZero));
        }

        see = residualTotal.Sum() / (stockPctReturns.Count - 2);
        see = Math.Sqrt(see);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }

    return Math.Round(see, 2, MidpointRounding.AwayFromZero);
}

As you can see, I'm trying to round the values down so I can keep the numbers small to work with them but no matter what I have tried, I keep getting NaN as the only result. Am I missing something here?

Upvotes: 0

Views: 845

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125620

You're probably trying to get square root from negative value, which causes Math.Sqrt to return double.NaN. Use Math.Abs before calling Math.Sqrt:

residualSquare = Math.Sqrt(Math.Abs(Convert.ToDouble((marketPctReturns.ElementAt(i) - stockPctReturns.ElementAt(i)), culture)));

Upvotes: 4

Related Questions