Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fast way to compute n times 10 raised to the power of minus m

Tags:

c++

math

pow

I want to compute 10 raised to the power minus m. In addition to use the math function pow(10, -m), is there any fast and efficient way to do that?

What I ask such a simple question to the c++ gurus from SO is that, as you know, just like base 2, 10 is also a special base. If some value n times the 10's power minus m, it is equivalent to move n's decimal point to the left m times. I think it must be a fast and efficient way to cope with.

like image 994
GoldenLee Avatar asked Sep 06 '25 10:09

GoldenLee


2 Answers

For floating point m, so long as your standard library implementation is well written, then pow will be efficient.

If m is an integer, and you hinted that it is, then you could use an array of pre calculated values.

You should only be worrying about this kind of thing if that routine is a bottleneck in your code. That is if the calls to that routine take a significant proportion of the total running time.

like image 136
David Heffernan Avatar answered Sep 09 '25 16:09

David Heffernan


Ten is not a special value on a binary machine, only two is. Use pow or exponentiation by squaring.

like image 43
Fred Foo Avatar answered Sep 09 '25 16:09

Fred Foo