
Database System Concepts
7th Edition
ISBN: 9780078022159
Author: Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher: McGraw-Hill Education
expand_more
expand_more
format_list_bulleted
Question
python.
Starter Code:
import numpy as np
import matplotlib.pyplot as plt
exp_approx = np.zeros(10)
abs_error = np.zeros(10)
rel_error = np.zeros(10)
N_cutoff = 0
# Save plot for grading
plot = plt.gca()
![In numerical methods, one source of error occurs when we use an approximation for a mathematical
expression that would otherwise be too costly to compute in terms of run-time or memory resources. One
routine example is the approximation of infinite series by a finite series that mostly captures the important
behavior of the infinite series.
In this problem you will implement an approximation to the exp(2) as represented by the following infinite
series,
exp(*)
Name
=
Your approximation will be a truncated finite series with N + 1 terms,
Input/Output
The setup code provides the following variables:
X
00
desired_rel_error
+0
Type
float
exp(x, N) =
Z"
Part 1
For the first part of this problem, you are given a random real number x and will investigate how well a finite
series expansion for exp(x) approximates the infinite series.
• Compute exp(2) using a finite series approximation with N = [0,9] CN (i.e. N is an integer).
• Save the 10 floating point values from your approximation in a numpy array named exp_approx.
exp_approx should be of shape (10.) and should be ordered with increasing N (i.e. the first entry of
exp_approx should correspond to exp(, N) when N = 0 and the last entry when N = 9).
n!
N
Part 2
For the second part of this problem, you are asked to find an integer value Noutoff € [0,9] such that the finite
series is guaranteed to have a relative error less than some desired amount. The relative error is with respect to
the true exp(2) value that would result from an infinite series. Newtoff should be the smallest integer that
satisfies the desired relative error constraint.
• First, save the absolute and relative errors for each value of N in abs_error and rel_error.
• Given a desired decimal relative error, desired_rel_error, find the smallest N that guarantees the
relative error is below desired_rel_error. Assign this N to a variable N_cutoff.
•
Plot the relative error vs. N (error on the y-axis and N on the x-axis). Make the y-axis log scale. You
should have 10 values. Provide appropriate formatting (e.g. labels, title, markers, et cetera).
7-0
7-11
I
Description
random real number where the function will be evaluated
float the error limit in computing the value of N
Your code snippet should define the following variables:
Name Type
Description
array giving your estimates for exp(x)
array giving the absolute error for using the taylor approximation
exp_approx 1-D Numpy Array
abs_error 1-D Numpy Array
rel_error 1-D Numpy Array
N_cutoff int
array giving the relative error for using the taylor approximation
the smallest N that satisfies the desired relative error constraint
semilogy plot of the relative error vs. N
plot
subplot
Your code snippet mote also generate the following plot
• Plot of relative error vs. N. log-scale on the y-axis (plt.senilogy). Provide appropriate axes labels and a
title. Save your plot to a variable plot.](https://content.bartleby.com/qna-images/question/840ac9d4-eb27-4280-b70d-21eed9a81895/65bf4566-7a2b-4d4c-aed2-60ffab9fe0c1/s747mo_thumbnail.png)
Transcribed Image Text:In numerical methods, one source of error occurs when we use an approximation for a mathematical
expression that would otherwise be too costly to compute in terms of run-time or memory resources. One
routine example is the approximation of infinite series by a finite series that mostly captures the important
behavior of the infinite series.
In this problem you will implement an approximation to the exp(2) as represented by the following infinite
series,
exp(*)
Name
=
Your approximation will be a truncated finite series with N + 1 terms,
Input/Output
The setup code provides the following variables:
X
00
desired_rel_error
+0
Type
float
exp(x, N) =
Z"
Part 1
For the first part of this problem, you are given a random real number x and will investigate how well a finite
series expansion for exp(x) approximates the infinite series.
• Compute exp(2) using a finite series approximation with N = [0,9] CN (i.e. N is an integer).
• Save the 10 floating point values from your approximation in a numpy array named exp_approx.
exp_approx should be of shape (10.) and should be ordered with increasing N (i.e. the first entry of
exp_approx should correspond to exp(, N) when N = 0 and the last entry when N = 9).
n!
N
Part 2
For the second part of this problem, you are asked to find an integer value Noutoff € [0,9] such that the finite
series is guaranteed to have a relative error less than some desired amount. The relative error is with respect to
the true exp(2) value that would result from an infinite series. Newtoff should be the smallest integer that
satisfies the desired relative error constraint.
• First, save the absolute and relative errors for each value of N in abs_error and rel_error.
• Given a desired decimal relative error, desired_rel_error, find the smallest N that guarantees the
relative error is below desired_rel_error. Assign this N to a variable N_cutoff.
•
Plot the relative error vs. N (error on the y-axis and N on the x-axis). Make the y-axis log scale. You
should have 10 values. Provide appropriate formatting (e.g. labels, title, markers, et cetera).
7-0
7-11
I
Description
random real number where the function will be evaluated
float the error limit in computing the value of N
Your code snippet should define the following variables:
Name Type
Description
array giving your estimates for exp(x)
array giving the absolute error for using the taylor approximation
exp_approx 1-D Numpy Array
abs_error 1-D Numpy Array
rel_error 1-D Numpy Array
N_cutoff int
array giving the relative error for using the taylor approximation
the smallest N that satisfies the desired relative error constraint
semilogy plot of the relative error vs. N
plot
subplot
Your code snippet mote also generate the following plot
• Plot of relative error vs. N. log-scale on the y-axis (plt.senilogy). Provide appropriate axes labels and a
title. Save your plot to a variable plot.
Expert Solution

This question has been solved!
Explore an expertly crafted, step-by-step solution for a thorough understanding of key concepts.
Step by stepSolved in 4 steps with 2 images

Knowledge Booster
Learn more about
Need a deep-dive on the concept behind this application? Look no further. Learn more about this topic, computer-science and related others by exploring similar questions and additional content below.Similar questions
- PLEASE HELP, PYTHON THANK YOU class Graph(object): def __init__(self, graph_dict=None): ################# # Problem 1: # Check to see if the graph_dict is none # if so, create an empty dictionary and store it in graph_dict ################## #DELETE AND PUT IN THE IF AND ASSIGNMENT STATEMENTS self.__graph_dict = graph_dict ################# # Problem 2: # Create a method called vertices and pass in self as the parameter ################## #DELETE AND PUT IN THE METHOD DEFINITION """ returns the vertices of a graph """ return list(self.__graph_dict.keys()) def edges(self): """ returns the edges of a graph """ ################# # Problem 3: # Return the results of the __generate_edges ################## #DELETE AND PUT IN THE RETURN STATEMENTSarrow_forwardCan you fix the error in the python code. import numpy as npimport matplotlib.pyplot as plt N = 20 # number of points to discretizeL = 0.15X = np.linspace(0, L, N) # position along the rodh = L / (N - 1) # discretization spacing C0t = 0.200 # concentration at x = 0Cth = 0.00000409D = 0.0000025t_avg = 0n = 0 tfinal = 300Ntsteps = 1000dt = tfinal / (Ntsteps - 1)t = np.linspace(0, tfinal, Ntsteps) alpha =( D * dt / h**2) C_xt = [] # container for all the time steps # initial condition at t = 0C = np.zeros(X.shape)C[0] = C0t C_xt += [C] for j in range(1, Ntsteps): N = np.zeros(C.shape) N[0] = C0t N[1:-1] = alpha*C[2:] + (1 - 2 * alpha) * C[1:-1] + alpha * C[0:-2] N[-1] = N[-2] # derivative boundary condition flux = 0 C[:] = N C_xt += [N] if ((Cth-0.000001) < N[-1]<(Cth+0.000001)): print ('Time=',t[j],'conc=',[N[-1]],'Cthr=',[Cth]) t_avg = t_avg+t[j] n = n + 1 # plot selective solutions if j in…arrow_forwardPython question please include all steps and screenshot of code. Also please provide a docstring, and comments throughout the code, and test the given examples below. Thanks. Suppose that you are given a list of strings representing a deck of 52 cards. Write afunction called bridgeHands() which takes the list as its only parameter. It shuffles the listand divides it into 4 hands (tuples) of 13 cards each. It returns a dictionary in which thekeys are the strings 'North', 'South', 'East', and 'West', with each key corresponding to adifferent one of the hands.arrow_forward
- Given an integer representing a 10-digit phone number, output the area code, prefix, and line number using the format (800) 555-1212. Ex: If the input is: 8005551212 the output is: (800) 555-1212 Hint: Use % to get the desired rightmost digits. Ex: The rightmost 2 digits of 572 is gotten by 572 % 100, which is 72. Hint: Use // to shift right by the desired amount. Ex: Shifting 572 right by 2 digits is done by 572 // 100, which yields 5. (Recall integer division discards the fraction). For simplicity, assume any part starts with a non-zero digit. So 0119998888 is not allowed.arrow_forwardJava - Given list: ( 4, 7, 18, 48, 49, 56, 66, 68, 79 )arrow_forwardWhy my code given me error’s # Python code to draw snowflakes fractal. import turtle import random # setup the window with a background color wn = turtle.Screen() wn.bgcolor("cyan") # assign a name to your turtle elsa = turtle.Turtle() elsa.speed(15) # create a list of colours scolor = ["white", "blue", "purple", "grey", "magenta"] # create a function to create different size snowflakes def snowflake(size): # move the pen into starting position elsa.penup() elsa.forward(10*size) elsa.left(45) elsa.pendown() elsa.color(random.choice(sfcolor)) # draw branch 8 times to make a snowflake for i in range(8): branch(size) elsa.left(45) # create one branch of the snowflake def branch(size): for i in range(3): for i in range (3): elsa.forward(10.0*size/3) # draw branch 8 times to make a snowflake for i in range(8): branch(slice) elsa.left(45) # create one branch of the snowflake def branch (size): for…arrow_forward
- FIX THIS CODE Using python Application CODE: import csv playersList = [] with open('Players.csv') as f: rows = csv.DictReader(f) for r in rows: playersList.append(r) teamsList = [] with open('Teams.csv') as f: rows = csv.DictReader(f) for r in rows: teamsList.append(r) plays=len(playersList) for i in range(plays): if playersList[i]['team']=='Argentina' and int(playerlist[i]['minutes played'])<200 and int(playersList[i] ['shots'])>20: print(playersList[i]['last name']) c0=0 c1=0 c2=0 for i in range(len(teamsList)): if int(teamsList[i]['redCards'])==0: c0=c0+1 if int(teamsList[i]['redCards'])==1: c1=c1+1 if int(teamsList[i]['redCards'])==2: c2=c2+1 print("Number of teams with zero redcards:",c0) print("Number of teams with zero redcards:",c1) print("Number of teams with zero redcards:",c2) ratio=0 for i in range(len(teamsList)): if int(teamsList[i]['games']>3) and if int(teamsList[i]['goalsFor'])/int(teamsList[i]['goalsAgainst'])<ratio:…arrow_forwardmain.py Load default template... 1 from random import randint 3 class RandomNumbers: # Type your code here. 4 5 main ": 6 if low = int(input()) high = int(input()) name 7 8 9 numbers = RandomNumbers() numbers. set_random_values(low, high) numbers.get_random_values() 10 11 12arrow_forwardimport numpy as np%matplotlib inlinefrom matplotlib import pyplot as pltimport mathfrom math import exp np.random.seed(9999)def is_good_peak(mu, min_dist=0.8): if mu is None: return False smu = np.sort(mu) if smu[0] < 0.5: return False if smu[-1] > 2.5: return False for p, n in zip(smu, smu[1:]): #print(abs(p-n)) if abs(p-n) < min_dist: return False return True maxx = 3ndata = 500nset = 10l = []answers = []for iset in range(1, nset): npeak = np.random.randint(2,4) xs = np.linspace(0,maxx,ndata) ys = np.zeros(ndata) mu = None while not is_good_peak(mu): mu = np.random.random(npeak)*maxx for ipeak in range(npeak): m = mu[ipeak] sigma = np.random.random()*0.3 + 0.2 height = np.random.random()*0.5 + 1 ys += height*np.exp(-(xs-m)**2/sigma**2) ys += np.random.randn(ndata)*0.07 l.append(ys) answers.append(mu) p6_ys = lp6_xs =…arrow_forward
- import numpy as np # Given current stock pricecurrent_price = 163.02 # Simulate future stock pricesnum_samples = 1000 # You can adjust this number based on your needsgrowth_rate_samples = np.random.lognormal(mean=-0.8404, sigma=2.5, size=num_samples)future_prices = current_price * np.exp(growth_rate_samples) # Print or visualize the simulated future pricesprint(future_prices) i cant get an answer , im keeping errorsarrow_forwardWhen I run this code it says there is an error. Can anyone help point out why I am getting an error for this code? from Artist import *from Artwork import *if __name__ == "__main__":mylist = input().split(" ")user_artist_name = str(mylist[0]+" "+mylist[1])user_birth_year = int(mylist[2])user_death_year = int(mylist[3])#mylist1 = mylist(4:-1)user_title = ""for i in mylist[4:-1]:user_title+=i+" "#user_title = str(mylist[4:-1])user_year_created = int(mylist[-1])user_artist = Artist(user_artist_name,user_birth_year,user_death_year)new_artwork = Artwork(user_title, user_year_created, user_artist)new_artwork.print_info() Here is the error message: Traceback (most recent call last): File "main.py", line 7, in <module> user_birth_year = int(mylist[2]) IndexError: list index out of rangearrow_forwardgcd(5x+7y,2x+3y) = ?arrow_forward
arrow_back_ios
arrow_forward_ios
Recommended textbooks for you
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education

Database System Concepts
Computer Science
ISBN:9780078022159
Author:Abraham Silberschatz Professor, Henry F. Korth, S. Sudarshan
Publisher:McGraw-Hill Education

Starting Out with Python (4th Edition)
Computer Science
ISBN:9780134444321
Author:Tony Gaddis
Publisher:PEARSON

Digital Fundamentals (11th Edition)
Computer Science
ISBN:9780132737968
Author:Thomas L. Floyd
Publisher:PEARSON

C How to Program (8th Edition)
Computer Science
ISBN:9780133976892
Author:Paul J. Deitel, Harvey Deitel
Publisher:PEARSON

Database Systems: Design, Implementation, & Manag...
Computer Science
ISBN:9781337627900
Author:Carlos Coronel, Steven Morris
Publisher:Cengage Learning

Programmable Logic Controllers
Computer Science
ISBN:9780073373843
Author:Frank D. Petruzella
Publisher:McGraw-Hill Education