1

I'm new to this forum, but I wanted to post this question hoping to know if anyone has come across it.

Is there a formula in math to round down to the closest power of ten?

For example, $n$ : the number, $r$: the round value. if $n = 101\Rightarrow r = 100$. if $n = 322\Rightarrow r = 100$. if $n = 1200\Rightarrow r = 1000$. if $n = 77\Rightarrow r = 10$.

We need this in finance business, where trades are bought in lot sizes of $10, 100, 1000$ etc.

Barry Cipra
  • 79,832

3 Answers3

2

If you always round to the largest previous power of 10, use $$r=10^{\lfloor\log_{10}(n)\rfloor},$$ where $\lfloor x\rfloor$ is the floor function.

AugSB
  • 5,007
1

I assume you want the order of magnitude of a given integer, $x$.

Fortunately, $m:=\lfloor \log_{10}(x)\rfloor$ gives exactly that. ($\lfloor • \rfloor$ is the floor function)

You can then consider $10^m$ for the nearest (lower) power of 10.

0

It sounds like you have to implement the answer as a script in order to use it. Here is how it can be done in python3:

from math import floor, log

def tenpow(x):
    return 10**(floor(log(x,10)))

tenpow(456)

This returns the powers of ten as desired. However, there is a problem - log(1000,10) in python returns 2.999999 not 3, which 'floors' to 2. But, if you write it 10**(floor(round(log(x,10)))) you get the wrong power of ten if the log result rounds up for other values. What is the remedy for this?

EDIT:

def tenpow(x):
    if x > 0:
        return 10**(len(str(x))-1)
    else:
        return 0

tenpow(345)

A better technique, as suggested by Barry Cipra.

  • 2
    As long as $n$ is an integer, you can safely add $1/2$, i.e., compute $\lfloor \log_{10}(n+{1\over2})\rfloor$. – Barry Cipra May 02 '16 at 22:58
  • Intriguing, will test... –  May 02 '16 at 23:00
  • Does python allow you to simply count the number of digits in an integer? Because it's certainly easier to see that $1234567$ has $7$ digits (so it should round down to $10^{7-1}$) than it is to compute $\log_{10}(1234567)\approx6.091514664$ and then throw away most of the effort. – Barry Cipra May 03 '16 at 00:01
  • Yes, of course, that's the simplest way to do it. –  May 03 '16 at 00:47
  • 1
    If by "easier" we mean "takes less execution time", I am not so sure:\begin{align} &\text{>>> timeit.timeit('10(len(str(11131719232931*37))-1)', number = 100000)}\ &\text{0.2725730583184145}\ &\text{>>> timeit.timeit('10(floor(log(11131719232931*37,10)))', 'from math import floor, log', number = 100000)}\ &\text{0.2457657722355293} \end{align} – David K May 03 '16 at 01:58