"for" with step "float": TypeError: 'float' object can not be interpreted as an integer

0

I want to loop from 0 to 100 with step 0.1:

for x in range(0, 100, 0.1):
    a = cos(radians(x))

But I get this error:

  

TypeError: 'float' object can not be interpreted as an integer

How can I loop through step float?

    
asked by anonymous 08.10.2018 / 20:06

2 answers

2

I've been able to do something that may be what you need.

from math import cos, radians

for x in (x * 0.1 for x in range(0, 1000)):
    print(x)
    a = cos(radians(x))

print(a)

Code would look something like this

SUGGESTION

Using a decimal number in this case can lead to potential errors with the floating point question. You can use the Numpy library by making use of the arange function that works similarly to for

>>> import numpy as np
>>> np.arange(0.0, 1.0, 0.1)
array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9])

Extra Tip

To avoid the issue of floating-point error, you can use Numpy's linspace function.

>>> import numpy as np
>>> np.linspace(0, 1, 11)
array([ 0. ,  0.1,  0.2,  0.3,  0.4,  0.5,  0.6,  0.7,  0.8,  0.9,  1. ])

Source: link

    
08.10.2018 / 20:21
2

For sampling purposes only notice the inconsistency of the result of this implementation of a generator that performs the sum of integers and floating-point numbers.

def _range(initial, end = float("inf"), step = 1):
    act = initial
    while (act < end):
        yield act
        act += step

for x in _range(0, 1, 0.1):
    print(x)

0
0.1
0.2
0.30000000000000004
0.4
0.5
0.6
0.7
0.7999999999999999
0.8999999999999999
0.9999999999999999

Read this answer for more information: link

    
08.10.2018 / 20:39