循环以十的幂次减小值

时间:2019-11-18 10:14:07

标签: python loops increment

我正在寻找一种Python的方法来在循环中将值减小为10的幂。 例如,初始值为x0 = 3e-5。我想在k上进行如下循环:

k = 1 : x1 = 2e-5
k = 2 : x2 = 1e-5
k = 3 : x3 = 9e-6
k = 4 : x4 = 8e-6
...

我该怎么办?

2 个答案:

答案 0 :(得分:1)

import math

def magnitude(x):
    return int(math.log10(x))

def decrement(x):
    start = int(str(x)[0])
    if start == 1:
        start = 10
    end = magnitude(x)
    return float(f"{start-1}e{end-1}")

x0 = 3e-5

for i in range(15):
    print(f"k = {i} : x{i} = {x0}")
    x0 = decrement(x0)

输出:

k = 0 : x0 = 3e-05
k = 1 : x1 = 2e-05
k = 2 : x2 = 1e-05
k = 3 : x3 = 9e-06
k = 4 : x4 = 8e-06
k = 5 : x5 = 7e-06
k = 6 : x6 = 6e-06
k = 7 : x7 = 5e-06
k = 8 : x8 = 4e-06
k = 9 : x9 = 3e-06
k = 10 : x10 = 2e-06
k = 11 : x11 = 1e-06
k = 12 : x12 = 9e-07
k = 13 : x13 = 8e-07
k = 14 : x14 = 7e-07

根据需要。

答案 1 :(得分:0)

这是一种方法:

import math
def get_base(x):
    pow = math.log(x,10)
    pow = math.floor(pow)
    base = round(x / (10 ** pow))
    if base == 1:
        return 9 * (10 ** (pow - 1))
    else:
        return (base - 1) * (10 ** pow)

x = 3e-5
for _ in range(10):
    print(x)
    x = get_base(x)

输出:

3e-05
2e-05
1e-05
9e-06
8e-06
7e-06
6e-06
4.9999999999999996e-06
4e-06
3e-06