You are on page 1of 2

x=float(input('Enter a number = ')) x=float(input('Enter a number = ')) import random def fact_smp(n):#simple

eps=0.01; """cube root of positive number greater than 1""" def roll_coin(): fact=1
step=0.001; eps=0.1 """A function to toss a coin""" for i in range(1,n+1):
i=0; low=1 return int(random.uniform(0.5,1.5)) fact*=i
while abs(x)-i**3>eps: high=x heads, tails, up=0, 0, 0 return fact
i+=step; guess=(low+high)/2 for i in range(10000): def Fib_smp(n):
while abs(x-guess**3)>eps: res=int(roll_coin()) Fib1=0
if abs(x)-i**3<=eps: print('guess = ',guess, 'low = ',low,'high =',high) if res==0: Fib2=1
if x>0: if guess**3>=abs(x): heads+=1 for i in range(3,n+1):
print('Approx Cube root is = ',i) high=guess elif res==1: Fib=Fib1+Fib2
else: else: tails+=1 Fib1, Fib2=Fib2, Fib
print('approx cube root is = ', -i) low=guess else: return Fib
else: guess=(low+high)/2 up+=1 for i in range(3,10):
print('No solution!') if abs(x-guess**3)<=eps: print('number of heads = ', heads) print(Fib_smp(i))
print('Approx Cube root is = ',guess) print('number of tails = ', tails)
import random import math
def findx(a,b): """overflow and underflow""" def fact_rec(n):#recursion ee=math.e
x=random.uniform(a,b) ov=1; if n>0: def Inf(n):
return x und=1; return n*fact_rec(n-1) if n==0:
def f(x): for i in range(1100): if n==0: return ee-1
return x**2-5*x+6 ov*=2.0; return 1 if n>0:
a, b=0, 4 # Solution will be searched in [a,b] und/=2; def Fib_rec(n): return ee-n*Inf(n-1)
eps=0.001 print('i = ',i) if n>2: import pylab
max_guess=10000 print('ov = ',ov) return Fib_rec(n-1)+Fib_rec(n-2) nn=[]
for i in range(max_guess+1): print('und = ',und) if n==1: inti=[]
x=findx(a,b) """Checking machine precision""" return 0 for i in range(20):
if abs(f(x))<eps: eps=10**(-1) if n==2: nn.append(i)
print('Number of steps = ',i) for m in range(30): return 1 inti.append(Inf(i))
print('solution = ',x) eps*=10**(-1) for i in range(1,10): pylab.plot(nn,inti)
break if 1+eps==1: print(Fib_rec(i)) pylab.show()
if i==max_guess: print('machine precision = ',eps) def sinr(x,n):
print('No real solutions from ',a,' to ',b) break if n==0: import numpy as np
return x import pylab as pl
"""Exhaustive Search for finding roots in [a,b]""" Int;float;bool,str;bytes N=30
if n>0:
def f(x): #This defines a function return sinr(x,n-1)\ I=[0]*(N+1)
return x**3-5*x**2-100 for n in range(N,0,-1):
+(-1)**n*x**(2*n+1)/fact_rec(2*n+1)
a, b=-10, 100 # Solution will be searched in [a,b] import pylab as pl I[n-1]=(np.e-I[n])/(n)
eps, step=0.01, 0.0001 x=pl.linspace(-10,10,1001) import time n = range(N+1)
N=int((b-a)/step) # Number of Steps in [a,b] y1=x**1*pl.sin(x) t0=time.clock() pl.plot(n,I)
flag=0 y1/=max(y1) for i in range(10000000): pl.xlabel('n')
for i in range(0,N+1): y2=x**2*pl.sin(x) x=2 pl.ylabel('$I(n)$')
x=step*i y2/=max(y2) t1=time.clock() pl.title('Back Integration')
if abs(f(x))<eps: y3=x**3*pl.sin(x) print('time t =',t1-t0)
print('One solution is = ',x) y3=y3/max(y3) def powerset(input):
flag=1 pl.plot(x,y1,label='$x^{1}\sin x$',linestyle='-') import math A=[[]]
if flag==0: pl.plot(x,y2,label='$x^{2}\sin x$',linestyle='-- try: B=[]
print('No real solutions from ',a,' to ',b) ') i=1 for m in input:
pl.plot(x,y3,label='$x^{3}\sin x$',linestyle='-.') k=1.0 for n in A:
"""Bisection Search for finding roots in [a,b]""" pl.legend(loc='lower center') while i!=0: B=[n+[m]]
def f(x): #This defines a function pl.xlabel('x') k=math.exp(i) A=A+B
return x**2-5*x+6 pl.ylabel('$x^n\sin x$') i=i+0.1 return A
a, b=2.1, 3.1 # Solution will be searched in [a,b] pl.title('several plots') except Exception as e:
pl.show() print("Error1: ",str(e)) Module:math;cmath;random
eps=0.001
import pylab as pl print("k=",k) Package:pylab;numpy;scipy
precision=0.00001
x=pl.linspace(-10,10,1001) print("i=",i) Library:sympy;matplotlib
c=(b+a)/2 # First middle value of x
while abs(f(c))>eps: st=['-','--','-.','-',':']
import numpy as np
if (f(a)>0 and f(c)>0) or (f(a)<0 and f(c)<0): for n in range(1,5):
import matplotlib.pyplot as plt
a=c y=x**n*pl.sin(x)
from mpl_toolkits.mplot3d import Axes3D
elif (f(b)>0 and f(c)>0) or (f(b)<0 and f(c)<0): y/=max(y)
ax = plt.subplot(111, projection='3d')
b=c pl.plot(x,y,label='$x^{}\sin x$'.format(n),\
L, n = 2, 400
c=(b+a)/2 # New middle value of x linewidth=n/2,linestyle=st[n])
x = np.linspace(-L, L, n)
if abs(b-a)<precision: pl.legend(loc='lower center')
y = x.copy()
break pl.xlabel('x')
X, Y= np.meshgrid(x, y)
if abs(f(c))<=eps: pl.ylabel('$x^n\sin x$')
A = np.double(0.1)
print('solution found is = ',c) pl.title('several plots')
Z = np.exp(-(X**2+Y**2))
else: pl.show()
ax.plot_wireframe(X, Y, Z)
print('No real solutions from ',a,' to ',b) #ax.plot_surface(X, Y, Z)
import numpy as np
import matplotlib.pyplot as plt plt.show()
"""Secant method for finding roots in [a,b]"""
def f(x): #This defines a function from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure() x=0 s=str(input('Enter a phrase: '))
return x**2-5*x+6 y=1 abbrev= s[0].upper()
xn2, xn1=4, 5.1 # Solution will be searched in [a,b] ax = fig.add_subplot(111, projection='3d')
# Plot a helix along the x-axis count=0 for i in range(1, len(s)):
eps=0.01 print('100 Fib no are' ) if (s[i] == ' ' or s[i] =='-'):
precision=0.00001 n = 1000
theta_max = 8 * np.pi for count in range(0,100): characters = s[i + 1].upper()
xn=xn1-f(xn1)*(xn1-xn2)/(f(xn1)-f(xn2)) print(x) abbrev = abbrev + characters
while abs(f(xn))>eps: theta = np.linspace(0, theta_max, n)
x = theta F=x+y print(abbrev)
xn=xn1-f(xn1)*(xn1-xn2)/(f(xn1)-f(xn2)) x=y
xn2,xn1=xn1,xn z = np.sin(theta)
y = np.cos(theta) y=F
if abs(xn1-xn2)<precision:
break ax.plot(x, y, z, 'b')
if abs(f(xn))<=eps: ax.plot(x, y, 0, color='r')
print('solution found is = ',xn) ax.plot(x, [0]*n, z, color='m')
plt.show()
import pylab as pl orbitals=["1s","2s","2p","3s","3p","4s",\ from numpy import sin
def factorial(n): "3d","4p","5s","4d","5p",\ from numpy import exp
if n <= 0: "6s","4f","5d"] import pylab as pl
return 1 electrons=[2,2,6,2,6,2,10,6,2,10,6,2,14,10] def f(x):
else: atomic_number=int(input('Enter atomic number: ')) return sin(x)
return n*factorial(n-1) while atomic_number<1: #Test 1 and test 2
def expf(x,N): print('Enter a positive number.') def integral(a,b,delta_x):
term=0 atomic_number=int(input('Enter atomic number: ')) N=int((b-a)/delta_x)
ans=1 while atomic_number>80: Sum=f(a)
for i in range(1,N ): print('Enter atomic number between 1 and 80') for i in range(1,N):
term= (-x)**(i)/factorial(i) atomic_number=int(input('Enter atomic number: ')) Sum += 2*f(a+i*delta_x)
ans=ans+term sum=0 Sum += f(b)
return ans i=0 Integral_1=(delta_x*Sum)/2
def integral(xc,N): ec=[] return Integral_1
a=0 for o in orbitals: Integ1=[]
b=xc if sum<=atomic_number-1: Integ2=[]
delta_x=(b-a)/N sum=electrons[i]+sum dx=pl.linspace(0.0001,0.1)
Sum=expf(a,N) e=orbitals[i-1],electrons[i-1] for i in dx:
for i in range(1,N): ec.append(e) I1=integral(0,10*22/7,i)
Sum += 2*expf(a+i*delta_x,N) i=i+1 Integ1.append(I1)
Sum += expf(b,N) d=sum-atomic_number I2 =integral(0,9*22/7,i)
Integral_1=(delta_x*Sum)/2 if d>=0: Integ2.append(I2)
return Integral_1 electrons[i-1]=electrons[i-1]-d Integ1/=max(Integ1)
xc=[2,18,15,20,50] e1=(orbitals[i-1],electrons[i-1]) Integ2/=max(Integ2)
for item in xc: ec.append(e1) pl.plot(dx,Integ1,label='Integral ',linestyle='--')
E=[] print('The electronic configuration is:') pl.plot(dx,Integ2,label='Integral ',linestyle='-')
for m in range(1,50+1): print(ec[1:]) pl.legend(loc='best')
I=integral(item,m) pl.xlabel('$\Delta x$')
error=I-1 def f(x,y): pl.ylabel('Integral')
E.append(error) return x**2-x-y-6 pl.title('Variation of integral ')
m = pl.linspace(1,51) def g(x,y): pl.show()
pl.plot(m,E,label='$xc={}$'.format(item)) return y+2*x-6
pl.legend(loc='best') a,b=-100,100 hbar=1.054*10**-34
pl.xlabel('No of terms in taylor expansion') eps, step=0.0001,0.1 pi=22/7
pl.ylabel('$Error$') N=int((b-a)/step) L=1*10**-9
pl.title('Limit of integration=xc') for i in range(-N,N): print('The length is', L/(1*10**-9),'nm.')
pl.show() for j in range(-N,N): U=4*1.6*10**-19
x=step*i print('The potential energy is',U/(1.6*10**-19),'eV.')
a=float(input('Enter the value of a: ')) y=step*j n=3
b=float(input('Enter the value of b: ')) if abs(f(x,y))<eps and abs(g(x,y))<eps: print('n =',n)
c=float(input('Enter the value of c: ')) print('The roots are', x,y) m=9.11*10**-31
d=b*b-4*a*c d0=0
eps=0.02 """sin function""" E0=n**2*pi**2*hbar**2/(2*m*L**2)
step=0.001 def factorial(n): print('Ground state energy',E0/(1.6*10**-19),'eV.')
ans=0.0 if n <= 0: d1=hbar/((2*m*(U-E0))**0.5)
while abs(ans**2-d) >= eps and ans<=d: return 1 E1=n**2*pi**2*hbar**2/(2*m*(L+2*d1)**2)
ans=ans+step else: d2=hbar/((2*m*(U-E1))**0.5)
if abs(ans**2-d)>=eps: return n*factorial(n-1) E2=n**2*pi**2*hbar**2/(2*m*(L+2*d2)**2)
print('Sorry failed to find roots') x=float(input('Enter the angle: ')) while abs(E2-E1)>0.0001*E1:
else: N=int(input('Enter the number of terms: ')) d2=hbar/((2*m*(U-E1))**0.5)
x1=(-b-ans)/(2*a) pi=22/7 E2=n**2*pi**2*hbar**2/(2*m*(L+2*d2)**2)
x2=(-b+ans)/(2*a) rad=x*pi/180 d1=hbar/((2*m*(U-E2))**0.5)
print('The first root is: ', x1) ans=rad E1=n**2*pi**2*hbar**2/(2*m*(L+2*d1)**2)
print('The second root is: ', x2) term=0 print('Penetration length:',d1/(1*10**-9),'nm. The energy is'\
for i in range(1,N ): ,E1/(1.6*10**-19), 'eV.')
x = int(input('Enter : ')) term= (-1)**i * rad**(2*i+1)/factorial(2*i+1)
while x < 0: ans=ans+term
print('Sorry ! ' ) print(ans)
x = int(input('Enter : '))
if x == 0 or x == 1:
print('The facorial of', x, 'is', 1)
else:
factorial = 1
num = x
while num > 1:
factorial = factorial * num
num = num -1
print('facorial of', x, 'is', factorial)

List:lst.append(val); lst.extend(seq);
lst.inert(idx,val);lst.remove(val);
lst.pop([idx]), lst.sort(), lst.reverse() String:s.startswith(prefix[,start[,end]]);s.strip([chars]);
Set:s.update(s2);s.copy();s.add(key), s.endswith(suffix[,start[,end]]);s.patition(sep);
s.remove(key),s.discard(key);s.clear(); s.count(sub[,start[,end]]); s.find(sub[,start[,end]]);
s.pop();|(union);&(intersection). s.index(sub[,start[,end]]),s.is …();s.lower();s.title();
s.swapcase();s.casefold();s.capitalize();s.split([sep]);
Dict:d[key]=value;d.update(d2);d. s.center([width,fill});s.join(seq);s.encode(encoding);
key(); d.values();d.items(); s.ljust([width,fill}); s.rjust([width,fill});s.zfill([width])
d.pop(key);d.popitem(key,value);
d.get(key);d.setdefault(key) len(c);min(c);max(c);sum(c);sorted(c);val in c;
list[];tuple(); enumerate(c);zip(c1,c2);all(c),any(c);
dict{1:”one”,2:”two”}; range([start,]end[,step])
set{‘key1”,key2”}

You might also like