Professional Documents
Culture Documents
METHODS
ASSIGNMENT – 2
17ME260
Problem 2:
import math
y = [1, 0.994, 0.99, 0.985, 0.979, 0.977, 0.972, 0.969, 0.965, 0.96,
0.956, 0.952]
sumt = 0
sumy = 0
sumtt2 = 0
sumty = 0
y[i] = math.log(y[i])
sumt += t[i]
sumt2 += t2[i]
sumy += y[i]
sumty += t[i]*y[i}
xmean = sumt/12
ymean = sumy/12
xymean = sumty/12
x2mean = sumt2/12
b = -((xmean*ymean)-xymean)/(xmean*xmean-x2mean);
a = math.exp(ymean+b*xmean);
Problem 3:
import numpy as np
y= (9*(np.cos(theta)**2)+4*(np.sin(theta)**2))**0.5
return y
if __name__ == '__main__':
h_trap=0.01563 # Obtained using error formula for
trapeziodal rule, error less than 10**-6.
for i in range(n_trap+1):
if i==0:
trap+=f(0)
continue
if i==n_trap:
trap+=f(np.pi/2)
continue
trap+=2*f(i*step_trap)
for i in range(n_simp+1):
if i==0:
simp+=f(0)
continue
if i==n_simp:
simp+=f(np.pi/2)
continue
if i%2==1:
simp+=4*f(i*step_simp)
continue
simp+=2*f(i*step_simp)
Problem 1:
import numpy as np
import matplotlib.pyplot as plt
def get_data(n):
x , step = np.linspace(-1.0,1.0,n+1,retstep=True)
y1 = np.exp(-(x**2)/2)
y2 = (1+(x**2))**0.5
y3 = (1+25*(x**2))**-0.5
return (y1,y2,y3,step)
def fact(n):
if n==0:
return 1
return n*fact(n-1)
def get_coeffs(y):
diff=[]
diffs_0=[]
coeff=[]
y=np.asarray(y)
n=y.shape[0]
table={}
for i in range(n-1):
if i==0:
for j in range(n-1):
diff.append(y[j+1]-y[j])
diffs_0.append(diff[0])
table[i+1]=np.asarray(diff)
diff=[]
continue
yy=table[i]
for j in range(yy.shape[0]-1):
diff.append(yy[j+1]-yy[j])
diffs_0.append(diff[0])
table[i+1]=np.asarray(diff)
diff=[]
for i in range(len(diffs_0)):
coeff.append(diffs_0[i]/factorial(i+1))
return coeff
if __name__ == '__main__':
y1,y2,y3,step = get_data(5)
coeffs1 = get_coeffs(y1)
coeffs2 = get_coeffs(y2)
coeffs3 = get_coeffs(y3)
x = np.linspace(-1.0,1.0,60)
s1=(x+1.0)/step
s2=(x+1.0)/step
s3=(x+1.0)/step
r1=s1
r2=s2
r3=s3
p1=np.zeros_like(x)+y1[0]
p2=np.zeros_like(x)+y2[0]
p3=np.zeros_like(x)+y3[0]
for i in range(len(coeffs1)):
p1+=(coeffs1[i]*r1)
p2+=(coeffs2[i]*r2)
p3+=(coeffs3[i]*r3)
r1=r1*(s1-i-1)
#s2=s2*(s2-1)
#s3=s3*(s3-1)
y1,y2,y3,_ = get_data(59)
t = np.linspace(-1.0, 1.0, 60)
print(y1.shape)
print(p1.shape)
print(step)
plt.plot(t, y1, 'r') # plotting t, a separately
# plotting t, b separately
#plt.plot(t, c, 'g') plotting t, c separately
plt.show()
plt.plot(t, p1-y1, 'b')
plt.show()
"""
y=[-3,3,11,27,57]
y=np.asarray(y)
#x=np.linspace(-1.0,1.0,5)
coeffs1 = get_coeffs(y)
print(coeffs1)
s1=(x-y[0])/step
p1=np.zeros_like(x)+y[0]
for i in range(len(coeffs1)):
p1+=(coeffs1[i]*s1)
s1=s1-1
print(x)
print(p1)
"""