Home > Mobile >  Range at one order-of-magnitude in Python
Range at one order-of-magnitude in Python

Time:06-19

I want to print x at one order-of-magnitude. However, there is an error. The desired output is attached.

for x in range(0,1e-3):
    print(x)

The error is

<module>
    for x in range(0,1e-3):

TypeError: 'float' object cannot be interpreted as an integer

The desired output is

0
1e-6
1e-5
1e-4
1e-3

CodePudding user response:

You could use:

for i in range(5):
    print(10**(i-7) if i else 0)

output:

0
1e-06
1e-05
0.0001
0.001

CodePudding user response:

You can use map() to generate the powers of 10, and then you can use itertools.chain() to add the zero in front:

from itertools import chain

for x in chain([0], map(lambda x: 10**x, range(-7, -2))):
    print(x)

This outputs:

0
1e-07
1e-06
1e-05
0.0001
0.001

CodePudding user response:

You cannot create a range from a float. i.e 1e-3 = 0.001. What will be the iterations between 0-0.001? You can run from 6-0 i.e range(6,0,-1) and print(10**(-i))

CodePudding user response:

looks like you want the range to be logarithmic I would say do something like:

for exponent in range(-7, -2):
    print(10**exponent)

CodePudding user response:

Tossing my hat in the ring, in case you want to keep the scientific notation formatting:

for i in range(-7, -2):
    print(f"{round(10**i, 6):.1e}")

Output:

0.0e 00
1.0e-06
1.0e-05
1.0e-04
1.0e-03

Or, using .1E:

0.0E 00
1.0E-06
1.0E-05
1.0E-04
1.0E-03

CodePudding user response:

Not the most elegant, but this also works:

import numpy as np

for x in [0]   list(10.0**np.arange(-6,-2)):
    print(x)

Or without numpy:

for x in [0]   [10**i for i in range(-6,-2)]:
    print(x)
  • Related