Search code examples
vb.netdoublealgebraic-data-types

Getting NaN for a double datatype


I am trying to run some mathematical formula which has large values, so I am using the Double datatype. But still I am getting the answer as NaN if I input large values. So how can I solve this?

For example, if I pass Varx=3 and countx=1230 I get the result as NaN.

Public Function EulerForPro(ByVal Varx As Integer, ByVal Countx As Integer) As Double

    Dim Result1 As Double = 1
    Dim Result2 As Double = Varx
    Dim Result As Double = 0

    For i = 1 To Countx
        Result1 = Result1 + (Math.Pow(-1, i) * Math.Pow(Varx, (2 * i)) / factx(2 * i))
    Next
    For i = 1 To Countx
        Result2 = Result2 + (Math.Pow(-1, i) * Math.Pow(Varx, ((2 * i) + 1)) / factx((2 * i) + 1))
    Next
    Result = Result1 + Result2
    Label2.Text = Result1
    Label3.Text = Result2
    Label4.Text = Result
End Function

Solution

  • Use the logarithm of the results. It is standard practice for large numbers.

    So instead of multiplying a*b (which causes overflow), use

    Y = log(a) + log(b)