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

Time:10-22

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

CodePudding user response:

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

def find_exponent(n):
    return int(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) - 1)


Example math:
find_exponent(944)    -> 2
find_exponent(0.000921) -> -3
944*10^(-3 -(2) -1) = 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[17]: [0.9440000000000001, 0.968, 0.1032]

Full code:

import math


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


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


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

CodePudding user response:

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
  • Related