Galal
Galal

Reputation: 41

How to handle double numbers that exceeds double.Max in C#?

I am working with a method that returns a large double value (> 1e308) and then this value is multiplied by a small double value to obtain a reasonable number. My problem is how to handle the double values in C# that exceed (1.79E308) without getting Infinity output?

Upvotes: 1

Views: 670

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Try using logarithms (Log(1e308) == 709.196...): instead of

 double bigNumber = SomeMethod();          // double.PositiveInfinity
 double smallNumber = SomeOtherMethod();
 double result = bigNumber * smallNumber;  // double.PositiveInfinity

Implement

 double bigNumber = SomeMethodLog();                  // reasonable value
 double smallNumber = SomeOtherMethodLog();
 // bigNumber will be cancelled out with smallNumber
 double result = Math.Exp(bigNumber + smallNumber);   // reasonable value

Upvotes: 2

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112334

First multiply with small number. Then with large number

double x = ...; // The number to be multiplied.
double result = x * smallNumber * largeNumber;

Upvotes: 0

Azamat S
Azamat S

Reputation: 71

There are two ways. 1. you can switch to another type that handles such big numbers. But in future you will be able to find another one example where floating point decision breaks your calculations again. 2. Right way. You have to re-design (refactor) your application's calculation flow. Try to find out which part of your code works with big numbers, which part operate small numbers. Work with it separately, and combine results before finish.

Upvotes: 0

Related Questions