Warm tip: This article is reproduced from serverfault.com, please click

I am looking for a function that maps an integer X to 0.X without using a loop

发布于 2020-11-28 21:41:14

I am trying to come up with a function that maps an integer X to the decimal 0.X without using a loop.

Examples:

  • 4 -> 0.4
  • 65 -> 0.65
  • 1584 -> 0.1584

I figured I could do something like this:

def mapToDec(x):
  while x > 1:
    x = x / 10
  return x

However, I am looking for something more sophisticated that doesn't require a loop, something that would look like a mathematical function perhaps.

Questioner
alexandrosangeli
Viewed
0
Tavian Barnes 2020-11-29 05:48:28

You have shown that there is such a function by implementing one. If you want one without a loop, how about

def mapToDec(x):
    return x * 10 ** -(1 + math.floor(math.log10(x)))