0

def f(x):
    result = x**2+(x/2)
    return(result)


for x in range(0.1, 0.10, 0.001):
    print(f(x))


that's my code in python, but show this error: TypeError: 'float' object cannot be interpreted as an integer

Ladiv
  • 3
  • 2
  • 2
    @Ch3steR for-loops themselves can deal with floats fine. It's `range` that causes the problem. You could for example use `numpy.arange` instead. – Heike Mar 28 '20 at 07:27
  • @Heike Yes, Good point. Thanks for pointing it out. – Ch3steR Mar 28 '20 at 07:28

4 Answers4

1

Use a range of integers, and do arithmetic to map the integers into the float values that you want. For example, for floats 0.001 apart, you could use consecutive integers and divide by 1000.

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
1

if you need to use range for float.

one way is to import arange from Numpy

from numpy import arange
def f(x):
    result = x**2+(x/2)
    return(result)


for x in arange(0.1, 0.10, 0.001):
    print(x)

NB : in your case both start and end are same value (0.1) hence no output would be produced try changing the values to produce output.

  • This is undoubtedly cleaner and more maintainable than dividing the indexes from an integer range. If you don't want to import such a huge library for a small function, `arange` can be easily implemented in a few lines. `def arange(start, end, step): ; i = start ; while i < end ; yield i ; i += step` – Neven V. Mar 28 '20 at 06:36
  • 1
    To avoid floating point error accumulation, you could also do `def arange(start, end, step): ; n = int((end-start)/step) ; return (start + (end-start)*i/n for i in range(n))` – Neven V. Mar 28 '20 at 06:42
1

Use an integer range and scale it to your desired floating point value.

For example:

def f(x):
    result = x**2+(x/2)
    return(result)

for n in range(10,21):
    x = n * .001
    print(f'{x:.3f} {f(x):.6f}')
0.010 0.005100
0.011 0.005621
0.012 0.006144
0.013 0.006669
0.014 0.007196
0.015 0.007725
0.016 0.008256
0.017 0.008789
0.018 0.009324
0.019 0.009861
0.020 0.010400
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
0

rang(n) function's inputs should be an integer and it returns 0, 1, 2, ..., n-1 if your step is 1. So if you know how many iterations are needed for your algorithm you can use for and range() with integer input. Also, you can make a list of f's inputs(x) so just can use for in this way:

for x in my_list:
    print(f(x))

or you can use while in this way:

x = initial_valuse_of_x
while x <= limit_of_x:
   print(f(x))
   x = x + step

for example if you inputs are in range: 0.2 to 1 with steps 0.2:

x: 02, 0.4, 0.6, 0.8, 1
initial_valuse_of_x = 0.2
limit_of_x = 1
step = 0.2

EDIT: As was mentioned in comments, floating increment may leads to inaccurace result in while() solution.

Maryam
  • 119
  • 1
  • 1
  • 6