Using Python: Create a code to generate 1001 values between 0 and 10 (essentially, start from 0 and use increment 0.01) and for each value ? ∈ [0,10] calculate sin(?) and the derivative of ?(x) = sin(?) using the central difference method: ????(?)/?? = ?(?+0.01)−?(?−0.01) 2∙0.01 . Output the result in a file using the print command: print (?, ???(?) , ????(?), ??? =′ ′, ??? =′\ ? ′ , ???? = ??) Recall that the output file must be opened initially (and named: ff=open(…) ), and the closed ( ff.close() ) at the end of your script. Use excel to draw a graph of your result ????(?) vs. ? and convince yourself that you essentially obtained the ???(?) function. Note that the values for ? can be generated in a loop: for ? in range(1001): ? = ?·0.01. Also, to avoid having numbers with 16 decimal places (as the result of ???ℎ. sin(?) function) round ???(?) , ????(?) to 4 decimal places; utilize round command as: sinx_round=round( ???ℎ. sin(?),4), etc.
Here is the code to do so, i have used numpy to do the mathematical operations:
Here is the text file generated:
This is only a sample view, you can check it for yourself, it will be saved where you have stored the python notebook.
To check if the data resembles a cosine graph, we will plot it in python itself:
It resembles a cosine graph, so it is correct.
The codes are well commented and easy to understand, if the answer helped you please upvote and if you have any doubts please comment i will surely help. please take care of the indentation while copying the code. Check from the screenshots provided.
Code:
import numpy as np
# open the file
f= open("data.txt","w+")
# generate linearly spaced data
x = np.linspace(0,10,1001)
# using list comprehension ot generate a list having sin(x) for all
x
# and using the list comprehension ot generate a list having
derivative
# for sin(x), using the finite difference model
sinx = [round( np.sin(i), 4) for i in x]
derivate_sinx = [round( (np.sin(i+0.01) - np.sin(i-0.01))/0.02 , 4)
for i in x ]
# write the data to the file
print(x, sinx , derivate_sinx, sep='', end ='\n' , file=f)
# close the file
f.close()
here is the code to plot the graph:
import matplotlib.pyplot as plt
x = np.linspace(0,10,1001)
sinx = [round( np.sin(i), 4) for i in x]
derivate_sinx = [round( (np.sin(i+0.01) - np.sin(i-0.01))/0.02 , 4)
for i in x ]
plt.plot(x, derivate_sinx)
plt.ylabel('d(sinx)/dx')
plt.xlabel('x')
plt.show()
Get Answers For Free
Most questions answered within 1 hours.