0

I'm relatively new to Python, so my code is very simple.
I have a project to write code which approximates integrals using the rectangle rule, followed by the trapezium rule:

    a = float(input('Lower limit ---> '))

while True:
    b = float(input('Upper limit ---> '))

    if b > a:
        break
    elif a == b:
        print('Integral = 0.')
    else:
        print('Invalid input.')

N = float(input('Number of integral divisions ---> '))

h = float((b - a) / N)

print('For the integral in the range {} to {} with {} divisions, the step size is {}.'.format(a,b,N,h))


def f(x):
    return(np.exp(-x) * sin(x))

summation = (f(a) + f(b))

for points in range(a, N - 1):
    summation = summation + f(a + (points * h))

I = h * summation

print(I)

Near the end, I try to use a for loop from the initial limit to minus 1 the number of step sizes.
I've defined this as a float but it I keep getting the error

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

Any ideas how to fix this?

ahajib
  • 12,838
  • 29
  • 79
  • 120
Ryan J
  • 13
  • 1
  • `range` expects integer arguments, but you give it floating-point values. Either use `int`, not `float`, for `a` and `N`, or use something like `arange` or `linspace` from the NumPy package. – mkrieger1 Mar 27 '18 at 16:29

3 Answers3

0

a, b and N are floats. range does not allow its arguments to be floats so you will need to convert them to int:

for points in range(int(a), int(N - 1)):

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
0

The error message clearly states that you are using floats where an integer is wanted.

Read the documentation of range() - what lead you to believe is is capable of doing anything with floats?

There are unlimited floats between 1 and 2 - and still very many if you take the resolution of float into consideration - how should python be able to give you all of them as range?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • Nothing led me to believe it could. It was a complete lack of understanding of what Python IS capable of that led me to assume it could. Thanks for the help. – Ryan J Mar 27 '18 at 16:31
0

when you collect your a and N variables, you convert them in float:

a = float(input('Lower limit ---> '))
N = float(input('Number of integral divisions ---> '))

Then you try to iterate from a to N, but let's assume a=0.42 and n=3.14.
How do you expect python to behave?

print([x for x in range(0.42,3.14)]) # Raise TypeError: 'float' object cannot be interpreted as a

so you have to convert your float into integers (a = int(a), N = int(N)):

print([x for x in range(0,3)]) # prints [0, 1, 2]

or you can use numpy, and define 2 float values and the step between them:

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])
Gsk
  • 2,929
  • 5
  • 22
  • 29
  • you are even already working with numpy, so the latest solution should be the best to implement – Gsk Mar 27 '18 at 16:34