founding the precision of a float in python based on a different float number

Question:

So, let’s say there is a float number: 0.11910000

and here is a list of numbers: 11970, 12020, 12070, 12165, 12400, 11100

I need them to turn to: 0.11970, 0.12020, 0.12070, etc... this is based on the the the decimal point in the float number is 0.1191, if it were 1.191 then the numbers would have been 1.197, 1.202, 1.207....
There is another point, that the decimal point should be where the number has the closest value to the original float. meaning:

if we take 9.21 as the original float number and have 944 968 1032 as the number, it should be 9.44, 9.68, 10.32 instead of 9.44, 9.68, 1.032.

Now I have made a function after millions of tries, and my brain is so fried at this point the results are not even close. here is my embarrassing function:

def calculate_dec_place(num : float, original_num : float) -> float:
    return num / 10 ** len(str(int(round(num // original_num, -len(str(int(num // original_num))) + 1)))) - 1
Asked By: Erik Gelfat

||

Answers:

We need two functions, one of which finds the exponent of a number:

def find_exponent(n):
    return math.floor(math.log10(abs(n)))

find_exponent(0.01)  -2
find_exponent(0.1)   -1
find_exponent(1)      0
find_exponent(10)     1
find_exponent(100)    2

And another function that takes one number and shifts it so the exponent aligns:

def align_decimal(target: float, other: float) -> float:
    target_exponent = find_exponent(target)
    return other*10**(target_exponent - find_exponent(other))


Example math:
find_exponent(944)      = 2
find_exponent(0.000921) = -4
944*10^(-3 -(2))        = 0.000944

Example output:
align_decimal(0.000921, 944) 0.000944

We can now apply a list comprehension to get your answer:

def align_decimals(target: float, others: list[float]) -> list[float]:
    return [align_decimal(target, x) for x in others]

example:
align_decimals(9.21, [944, 968, 1032])
Out[50]: [9.44, 9.68, 1.032]

align_decimals(7.34, [0.101])
Out[51]: [1.01]

Full code:

import math


def find_exponent(n):
    return int(math.log10(abs(n)))


def align_decimal(target: float, other: float) -> float:
    target_exponent = 
Answered By: Tom McLean

Here is a fixed version of Tom McLeans’ find_exponent function:

import math
def find_exponent(n):
    a = math.log10(abs(n))-math.log10(5)
    b = math.ceil(a)
    if a == b:
        return int(a+1)
    else:
        return b

Example cases:

find_exponent(0.0501)
Out[482]: -1

find_exponent(0.049999999999)
Out[483]: -2

find_exponent(78.1)
Out[484]: 2

find_exponent(500)
Out[485]: 3
Answered By: Swifty
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.