Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Am I Getting NaN?

Tags:

c#

I'm going through my code and each time D1 ends up being NaN. The code looks fine to me, and I'm completely stumped...

double D1;
Data Data = new Data();

PriceSpot = 40;
Data.PriceStrike = 40;
Data.RateInterest = .03;
Data.Volatility = .3;
Data.ExpriationDays = 300;

D1 = 
    (
        Math.Log(PriceSpot/Data.PriceStrike) +
        (
            (Data.RateInterest + (Math.Pow(Data.Volatility,2)/2)) *
            (Data.ExpirationDays/365)
        )
    ) /
    (
        Data.Volatility *
        Math.Pow(Data.ExpirationDays/365,.5)
    );
like image 649
sooprise Avatar asked Dec 07 '22 02:12

sooprise


1 Answers

Data.Volatility * Math.Pow(Data.ExpirationDays/365,.5) is 0 since 300/365 as int equals to 0

Assuming ExpriationDays property is of type int indeed, it'll make the whole expression be 0.

For example:

[Test]
public void Test()
{
    var val = 300 / 365;

    Assert.That(val, Is.EqualTo(0));
}

Some comment about dividing by 0:

When dividing two 0 integers an exception will be thrown at runtime:

[Test]
public void TestIntDiv()
{
    int zero = 0;
    int val;

    Assert.Throws<DivideByZeroException>(() => val = 0 / zero);
}

When dividing two 0 doubles the result will be NaN and no exception will be thrown:

[Test]
public void TestDoubleDiv()
{
    double zero = 0;
    double val = 0 / zero;

    Assert.That(val, Is.NaN);
}
like image 174
Elisha Avatar answered Dec 29 '22 08:12

Elisha