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
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
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.
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.
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
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.