Issue
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
Solution
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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.