Integrate a function by the trapezoidal rule- Python

2024/9/22 5:30:50

Here is the homework assignment I'm trying to solve:

A further improvement of the approximate integration method from the last question is to divide the area under the f(x) curve into n equally-spaced trapezoids.

Based on this idea, the following formula can be derived for approximating the integral:

!(https://www.dropbox.com/s/q84mx8r5ml1q7n1/Screenshot%202017-10-01%2016.09.32.png?dl=0)!

where h is the width of the trapezoids, h=(b−a)/n, and xi=a+ih,i∈0,...,n, are the coordinates of the sides of the trapezoids. The figure above visualizes the idea of the trapezoidal rule.

Implement this formula in a Python function trapezint( f,a,b,n ). You may need to check and see if b > a, otherwise you may need to swap the variables.

For instance, the result of trapezint( math.sin,0,0.5*math.pi,10 ) should be 0.9979 (with some numerical error). The result of trapezint( abs,-1,1,10 ) should be 2.0

This is my code but It doesn't seem to return the right values.
For print ((trapezint( math.sin,0,0.5*math.pi,10)))
I get 0.012286334153465965, when I am suppose to get 0.9979
For print (trapezint(abs, -1, 1, 10))
I get 0.18000000000000002, when I am suppose to get 1.0.

import math
def trapezint(f,a,b,n):g = 0if b>a:h = (b-a)/float(n)for i in range (0,n):k = 0.5*h*(f(a+i*h) + f(a + (i+1)*h))g = g + kreturn gelse:a,b=b,ah = (b-a)/float(n)for i in range(0,n):k = 0.5*h*(f(a + i*h) + f(a + (i + 1)*h))g = g + kreturn gprint ((trapezint( math.sin,0,0.5*math.pi,10)))
print (trapezint(abs, -1, 1, 10))
Answer

Essentially, your return g statement was indented, when it should not have been.

Also, I removed your duplicated code, so it would adhere to "DRY" "Don't Repeat Yourself" principle, which prevents errors, and keeps code simplified and more readable.

import math
def trapezint(f, a, b, n):g = 0if b > a:h = (b-a)/float(n)else:h = (a-b)/float(n)for i in range (0, n):k = 0.5 * h * ( f(a + i*h) + f(a + (i+1)*h) )g = g + kreturn gprint ( trapezint( math.sin, 0, 0.5*math.pi, 10) )
print ( trapezint(abs, -1, 1, 10) )

0.9979429863543573
1.0000000000000002

https://en.xdnf.cn/q/119092.html

Related Q&A

Kivy module not found in vscode (Mac)

I have installed Kivy and when I used the IDLE app that came with Python I can import it and it runs perfectly. However, when I try to import it in vscode I get the error: ModuleNotFoundError: No modul…

How to get latest unique entries from sqlite db with the counter of entries via Django ORM

I have a SQLite db which looks like this:|ID|DateTime|Lang|Details| |1 |16 Oct | GB | GB1 | |2 |15 Oct | GB | GB2 | |3 |17 Oct | ES | ES1 | |4 |13 Oct | ES | ES2 | |5 |15 Oct | ES | ES3 …

What does this code %.8f% do in python? [duplicate]

This question already has answers here:What does % do to strings in Python? [duplicate](4 answers)Closed 6 years ago.I am editing a code line to pass the rate in quotes:OO000OO00O0O0O000 [rate]=O0O0OO…

How to append a selection of a numpy array to an empty numpy array

I have a three .txt files to which I have successfully made into a numpy array. If you are curious these files are Level 2 data from the Advanced Composition Experiment (ACE). The particular files are …

Error saving and loading a list of matrices

I have a list "data_list", and I would save it in order to load it in another script. First of all I converted it in an array, in this way:data_array = np.array(data_list)Then I saved it:np.s…

Trying to interact with HTML page elements, but none of them are found

Im trying to scrape a webpage using Selenium, but when I try to pass the XPath of a button, I get an error saying that this element does not exist. I tried with another website, and it worked perfectly…

Duplicating an XML element and adding it to a specific position in XML file using python

I have a xml file in which content looks like this: xml_content_to_search = <Document ProviderID="TD" DecimalMarker="comma" Website="https://erc-viewer.sap.com/"> &l…

How do I fix this Gets server error, which is causing display issues?

The list in the left column of ontariocourts311.ca, along with the body of the page under the image intermittently fail to display (which is fixed by refreshing the page). Im a Noob, and have tried var…

Installing Scipy for Windows

I am trying to install Scipy on my computer. I did it by using the command pip install Scipy. (pip & numpy are up-to-date and I am using Python 3.6) I also tried it with Pycharm, but it didnt worke…

Python Opencv, dont put circle on the video

I wrote the following script with OpenCVimport cv2 import numpy as npcap = cv2.VideoCapture(0) ix, iy = -1, -1def draw_circle(event, x, y, flags, param):global ixglobal iyix,iy = x,yif event == cv2.EVE…