Python Error Message trying to plot integral using semi-logarithmic plot

  math, matplotlib, numerical-methods, numpy, python

I’m new to Python and struggling. I get the error message "TypeError: only integer scalar arrays can be converted to a scalar index" when running my code.

I am trying to answer this question:

  1. Given the function f(x) = e^x+x^2, use the composite trapezium rule to compute the
    integral using n equally spaced sub-intervals. Write this into a function
    that takes f, a, b and n as inputs and returns the integral.

  2. Using the interval [a, b] = [0, 2] and the values n = 2p with p = 0, 1, …20, compute
    the integral and plot the result in dependence of n using a semi-logarithmic (in
    n) plot. In a different figure, plot the absolute difference between your numerical
    result and the exact value of the integral against n using a log-log plot. As always,
    add axis labels. Comment on your second figure.

This is what I have so far:

import math

def f(x):
    return math.exp(x)+x*x;
def trapezoidal(a,b,n):
    h=(b-a)/n

    integration=f(a)+f(b)

for i in range (1,n):
    k=a+i*h
    integration=integration+2*f(k)
   
integration=integration*h/2
return integration

#Input
    n=int(input("number of sub intervals"))
    a=float(input("lower bound of integration"))
    b=float(input("upper bound of integration"))

import numpy as np
import matplotlib.pylab as plt

p=np.linspace(0,20)
n=2**p

x=np.linspace(0,2,21)
y1=trapezoidal(0,2,n)
plt.plot(x,y1)`

Source: Python Questions

LEAVE A COMMENT