Question

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
Was it helpful?

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)

OTHER TIPS

You could try using the Decimal data type instead. It can hold an integer value of approximately 7,9 x 10^28 (the exact number is 2^96 - 1, since it can use 96 bits of its 128 for storing the integer part of a value). However, it's a complex data type and you should carefully consider how to use it in your code. Not all implicit conversions work, especially when using Double.

See MSDN on decimal for exact specifications of Decimal.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top