Reputation: 137
I am writing a program in C++ which includes very small floating point numbers. So, I have used double
to represent the numbers. But as the floating point numbers are multiplied in a loop, it results in the final product being 0. But I need to display the actual floating point number. How can I handle such numbers?
class myclass
{
private :
double value;
}
double calculate(count)
{
double key=this->value;
double prev_level=pow(2,level-1);
if(key-prev_level >=0)
key=key-prev_level;
int index= (2* key) + table[row_num][pos];
double num1=array_l1[index]; // array_l1 and array_l2 are of type double
double num2=array_l2[index];
std::pair<double,double> p = list[key].at(row_num);
double data=p.first;
prod1=num1 *data;
data=p.second;
prod2=num2 * data;
return prod1+prod2;
}
void compute()
{
double prod = 1;
for (int i = 0; i < count; i++)
{
myclass c1(count);
myclass c2(count+1);
double value= c1.calculate * c2.calculate();
}
}
I am not able to include all the code because of the size, but I hope this function can explain the problem I am facing. As the value of count
increases, the value of value
decreases. So for larger value of count
, I get a 0.
How can I display the actual value of value
?
Upvotes: 0
Views: 2734
Reputation: 26185
First check that you are using an output format that allows for scientific notation, not just a fixed number of digits after the decimal point.
If that still results in zero output, consider summing logarithms rather than multiplying the numbers directly.
If, for example, the objective is to compare ratios of products, you can complete the calculation in logarithms, without ever doing the exponentiation to return to the non-logarithm world.
If you just need to display the result, pick a large constant. Add the logarithm of the constant to the sum before doing the exponentiation, and include the constant in the display.
Upvotes: 2
Reputation: 154035
The floating point types use a fixed size representation. This has two immediate implications:
If you need more precision or a wider range you'll need a different representation. You might want to have a look at What Every Computer Scientist Should Know About Floating-Point Arithmetic.
Upvotes: 3