What is a good way to create a double from a coefficient and a power of 10? Or in other words, what is a good way to create a double from the significand and the exponent of a written scientific notation value at runtime?
Asked
Active
Viewed 356 times
0
-
4What's wrong with `coefficient * pow( 10.0, exponent)`? – Henrik Jan 28 '14 at 09:51
-
For power of _two_, you could use [std::ldexp](http://en.cppreference.com/w/cpp/numeric/math/ldexp), but for power of 10 `std::pow` is all you've got. – Jan Hudec Jan 28 '14 at 10:11
-
2There's no such thing as a "scientific notation value" - scientific notation is a textual representation of values. – molbdnilo Jan 28 '14 at 10:29
-
Indeed. So unless this involves some string handling routines, it doesn't make any sense. – Lundin Jan 28 '14 at 10:36
-
Thanks for noticing that. I fixed the phrasing in the question. – sFuller Jan 28 '14 at 17:47
-
`double d = 5.4313e6;` – Crowman Jan 28 '14 at 17:53
-
I'm talking about during runtime. Sorry for being so vague. – sFuller Jan 28 '14 at 22:51
1 Answers
3
Not sure about numerical quality, but the obvious way would be:
double make_double(double coefficient, int power)
{
return coefficient * pow(10.0, power);
}

unwind
- 391,730
- 64
- 469
- 606
-
If you are worried about numerical quality, then to play safe you could write a string and pass it to `strtod`. The precision of the coefficient might still cause problems, but there's not a lot you can do about inaccuracies that are already there in your input. – Steve Jessop Jan 28 '14 at 11:00