using python Challenge: Write a function that performs integration, using the 1/
ID: 3600971 • Letter: U
Question
using python
Challenge: Write a function that performs integration, using the 1/3rd rule, on a set of data provided in a list. Assume the data is equally spaced at&x; and the list holds the corresponding y data. As a test integrate the data -0.10, y = [1, 3,4, 2, 4, 8, 10, 10, 12,9, 8]. Your function should work for any data set. You will have to adjust for the fact that the 1/3 rule requires an even number of partitions. One approach is to integrate as much of the data as possible using the 1/3rd rule, and then use trapezoid rule for the rest of the dataExplanation / Answer
The 1/3rd rule is also called as Simpsons rule. Here's the code in python to use Simpsons rule over a list.
----------------------------------------------------------------------------------------------------------------
#!usr/bin/env python
def Simpsons( delta_x, list_y ) :
length = len(list_y);
# if list is of even length
if length % 2 == 0:
i = 1
result = 0 # initial result initialized to 0
# loop up to the last element of the list
while i < length - 1 :
if i % 2 == 0 : # if index is even like 0,2,4...
result = result + 2 * list_y[i]
else: # if index is odd like 1,3....
result = result + 4 * list_y[i]
i = i + 1 # loop control variable
result = result + list_y[0] + list_y[length-1] # adding first and last element
return ( (delta_x/3) * result ) # the actual Simpsons rule
# if list is of odd length
else :
i = 1
result = 0 # initial result set to 0
while i < length - 2: # looping over entire lest except last element
if i % 2 == 0: # if index is even 0,2,...
result = result + 2 * list_y[i]
else: # if index is odd 1,3,...
result = result + 2 * list_y[i]
i = i + 1 # loop control variable
sum = sum + list_y[0] + list_y[length - 2] # adding to result first and last but one element
return ( ( delta_x/3) * sum + ( ( ( list_y[ length - 1 ] + list_y[ length - 2 ])* delta_x )/2 ) ) # applying trapezoid area at the odd list data
print Simpsons(0.10, [1,3,4,2,4,8,10,10,12,9,8])
-------------------------------------------------------------------------------------------------------------------
/* hope this helps */ /* i have commented the code for your understanding */
/* if any queries please comment */
/* thank you */
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.