"for" with step "float": Typeerror: 'float' Object cannot be Interpreted as an integer

Asked

Viewed 1,982 times

0

I want to loop 0 to 100 with step 0.1:

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

But I get this mistake:

Typeerror: 'float' Object cannot be Interpreted as an integer

How can I make a loop with step float?

  • Have you considered implementing a generator?

3 answers

2


I’ve managed to do something that’s possibly 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 be something like that

SUGGESTION

Using a decimal number in this case can lead to possible errors with the floating point issue. You can use the library Numpy making use of the function arange that works in a similar way to the.

>>> 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 the function linspace numpy.

>>> 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: https://docs.scipy.org/doc/numpy/user/quickstart.html

  • Ok, I edited the above example to make it clearer. I see no point in using numpy if I just want to calculate the cos of each number in the range of 0.1... would have some other way?

  • @Rogériodec I edited the answer, I hope you may have solved your problem

  • 1

    In the first example for x in [x * 0.1 for x in range(0, 1000)]:, better for x in (x * 0.1 for x in range(0, 1000)): - this second is a "Generator Expression": each element is only created when it is used in for. With [ ] , Python first creates a list of all elements - allocating memory to everything, and then consumes the elements in the loop for external. The memory consumption difference is significant.

  • @jsbueno yes true, I didn’t notice at that point.

2

Only for sampling purposes notice the inconsistency of the result of this implementation of a generator that performs the sum of integers and floating point.

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: /a/11328/88315

0

It is possible to achieve the desired result using a generator ints and split the result:

    for x in range(1001):
         x = x/10
         print(x)

0.0

0.1

0.2

(...)

99.9

100.0

[Finished in 0.196s]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.