38
Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014 1 FORTRAN PROGRAMS for Physics Students (with THEORY and ALGORITHM) Department of Physics Panskura Banamali College Vidyasagar University West Bengal, India

FORTRAN Programs for Physics Students

Embed Size (px)

DESCRIPTION

A set of simple and special FORTRAN programs written for undergraduate and postgraduate physics students for their curriculum. Necessary theories, algorithms and graphical illustrations are added. If this helps the students in some way and the students are encouraged to play with the computer programs, the effort would be meaningful. Criticisms and any kind of feedback would be greatly appreciated.

Citation preview

Page 1: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

1

FORTRAN PROGRAMS for Physics Students

(with THEORY and ALGORITHM)

Department of Physics

Panskura Banamali College

Vidyasagar University

West Bengal, India

Page 2: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

2

Simple Programs

Area of a Triangle:

Theory:

For a triangle, if two sides and and the angle between them are given, the third side,

√ . The area of the triangle, √ , where

.

Algorithm:

1. Input: two sides a and b and adjacent angle

2. Covert the angle into radian, find the third side from formula

3. Calculate s, Calculate area from Heron’s formula

FORTRAN Program:

Prime Numbers:

Theory:

Prime numbers are those which are not divisible by any number except 1 and the same

number. For example, 3, 5, 7…. Here we check prime numbers between two numbers

Algorithm: 1. Do Loop starts from 2 up to n-1 2. Inside the loop, check if the number ‘n’ is divisible by any number 3. Set a counter to check how many times there are no divisors. 4. If the count = n-2, we find this is a prime number.

C Area of a Triangle: Heron’s Formula

C

write(*,*)'Give Two sides and the adjacent angle'

read(*,*)a,b,theta

x = 3.14*theta/180 ! Converting into radian

c = sqrt(a**2+b**2-2*a*b*cos(x))

s =(a+b+c)/2.

area = sqrt(s*(s-a)*(s-b)*(s-c))

write(*,*)'Area =', area

stop

end

Page 3: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

3

FORTRAN Program:

Square Number:

Theory:

This is to check if a given number is a perfect square, for example, . So we take a

number and calculate its square root, the result will be an integer when perfect square, else a

real number. If the result is a real number (and not an integer), the integer part squared again,

will not match with the original number. In case of perfect square number, this matches.

Algorithm: 1. Input: the number 2. Take square root and keep the integer part. 3. Square the Integer part (in step 2). 4. Check if the squared number (in step 3) matches with the given number.

FORTRAN Program:

C To find Prime Numbers

C

write(*,*)'Prime Numbers'

do 10 n=1,1000

k=0

do i=2,n-1

ii=mod(n,i)

if(ii.eq.0)go to 10

if(ii.ne.0)k=k+1

enddo

if(k.eq.n-2)write(*,*)n

10 continue

stop

end

C Check if a number is a perfect square

C

write(*,*)'give a number'

read(*,*)n

nsqrt=sqrt(real(n))

nsq=nsqrt*nsqrt

if(nsq.eq.n)then

write(*,*)'Perfect Square'

else

write(*,*)'NOT a Perfect Square'

endif

stop

end

Page 4: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

4

Armstrong Number:

Theory:

Armstrong number is a number such that the sum of its digits raised to the third power is equal to the number itself. For example, 153 is an Armstrong number, since .

Algorithm: 1. Set a counter. 2. For a three digit number, three nested do loop start for three integers. 3. Construct a number from three integers. 4. Take cubes of the integers and sum them inside the innermost loop. 5. Check if the sum matches with the constructed number. 6. Count how many Armstrong numbers are there between 0 and 999.

FORTRAN Program:

C Armstrong Number between 0 and 999

C

n=0

do i=0,9

do j=0,9

do k=0,9

ijk=i*100+j*10+k

i3j3k3=i**3+j**3+k**3

if(ijk.eq.i3j3k3)then

write(*,*)ijk

n=n+1

endif

enddo

enddo

enddo

write(*,*)'Total no. of Armstrong Numbers = ', n

stop

end

Page 5: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

5

Read a Number, Find the Digits:

Theory:

We have to read a number and find out its digits at different places. A decimal number is found

by multiplying by the powers of 10 with the digit in place and then summing. So the digits of a

decimal number can be found out by dividing the number by 10 and taking the remainder.

Next time, divide the number by 10 and take the integer part and repeat the steps. For

example, take the number 358, divide 358 by 10, the remainder is 8. Next time, consider

and take the integer part which is 35 and repeat the steps.

Algorithm: 1. Input: The Number, number of digits (n) 2. Start a do loop starting from 1 to n. 3. Find the remainder (Modulo 10). 4. Divide the number by 10 and retain the integer part for the next step. 5. Sum the digits as obtained.

FORTRAN Program:

C Read a Number and find the sum of its digits

C

write(*,*)'Give the number'

read(*,*)number

write(*,*)'How many digits?'

read(*,*)n

nsum=0

write(*,*)’Digits in reverse order’

do i=1,n

nd=mod(number,10)

number=number/10.

nsum=nsum+nd

write(*,*)nd

enddo

write(*,*)'Sum of digits = ', nsum

stop

end

Page 6: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

6

Palindrome Number:

Theory:

A Palindrome is some word or number or a phrase which when read from the opposite end,

appears the same (reflection symmetry, example, 34543, symmetry around 5 in the middle).

We here read a decimal number and find out its digits at different places. After finding the

digits we construct the number taking the digits in the reverse order. For example, given the

number 456, we construct the new number (this is not

palindrome number).

Algorithm: 1. Input: The Number, number of digits (n) 2. Store the Number. 3. Start a do loop starting from 1 to n. 4. Find the remainder (Modulo 10). 5. Divide the number by 10 and retain the integer part for the next step. 6. Do the sum after multiplying the digit with the appropriate power of 10 for that

place. 7. Check the sum with the stored number: If equal, Palindrome.

FORTRAN Program:

C Palindrome Number

C

write(*,*)'Give the number'

read(*,*)number

write(*,*)'Number of digits = ?'

read(*,*)n

number0=number ! To store the Number

nsum=0

do i=1,n

nd=mod(number,10)

number=number/10.

nsum=nsum+nd*10**(n-i)

write(*,*)'i = ',i,nd

endd

if(nsum.eq.number0)write(*,*)'Palindrome'

if(nsum.ne.number0)write(*,*)'Not Palindrome'

pause

end

Page 7: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

7

Fibonacci Numbers:

Theory: Fibonacci numbers are the series of numbers where each number is the sum of two previous

numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89….

The rule:

Algorithm: (Numbers up to 610, for example)

1. Input: Two initial numbers 0 and 1.

2. Start a do-loop. Obtain the 3rd number as the sum of first two numbers.

3. Now redefine the 2nd number as the 1st number and the 3rd number as the 2nd

number.

4. Obtain the 3rd number as the sum of newly defined 1st and 2nd numbers and repeat

inside the loop. Write down the numbers on the screen as they are obtained.

5. Check if the new number in the series is 610, then exist the loop and write the sum.

FORTRAN Program:

Golden Ratio = 1.6180…

C Fibonacci Numbers up to 610

C

n1=0

n2=1

n3=n2+n1

write(*,*)’Fibonacci Numbers’

write(*,*)n1

write(*,*)n2

write(*,*)n3

do while(n3.lt.610)

n1=n2

n2=n3

n3=n2+n1

write(*,*)n3

enddo

write(*,*)'Golden Ratio= ', float(n3)/n2

stop

end

Page 8: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

8

Sum of an Infinite Series

Exponential Series:

Theory: Taylor series expansion:

.............!4!3!2

1)exp(432

xxx

xx

Algorithm:

1. Input: , Tolerance value 2. Initial values: Sum = 0, Term = 1.0 3. Do Loop starts (n = 1, 2…)

4. New Term = Previous Term

5. Sum the terms. 6. Check: Absolute value of a term when less than tolerance, come out. 7. Write the sum.

FORTRAN Program:

C Exponential Series with tolerance value

C

write(*,*)'Give x and tolerance value'

read(*,*)x,tol

sum=0.0

term=1

do n=1,100

if(abs(term).lt.tol)go to 10

sum=sum+term

term=term*x/n

end do

10 write(*,*)’Calculated value, Actual value’

write(*,*)sum,exp(x)

stop

end

Page 9: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

9

Cosine Series:

Theory:

Taylor series expansion:

Algorithm:

1. Input: , tolerance value 2. Initial values: Sum = 0, Term 3. Do Loop starts (n = 1, 2….)

4. New Term = Previous term (

)

5. Sum the terms 6. Check: Absolute value of a term when less than tolerance, come out. 7. Write the sum.

FORTRAN Program:

C Sum of Cosine Series with tolerance value

C

write(*,*)'Give x and tolerence value'

read(*,*)x,tol

sum=0.0

term=1.0

do n=1,100

if(abs(term).lt.tol)go to 10

sum=sum+term

term=term*(-x**2/(2*n*(2*n-1)))

enddo

10 write(*,*)’Calculated value, Actual Value’

write(*,*)sum,cos(x)

stop

end

Page 10: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

10

Sine Series:

Theory:

Taylor series expansion of:

Algorithm:

1. Input: , tolerance value 2. Initial values: Sum = 0, Term 3. Do Loop starts (n = 1, 2….)

4. New Term = Previous term (

)

5. Sum the terms 6. Check: Absolute value of a term when less than tolerance, come out. 7. Write the sum

FORTRAN Program:

C Sum of Sine Series with tolerance value

C

write(*,*)'Give x and tolerence value'

read(*,*)x,tol

sum=0.0

term=x

do n=1,100

if(abs(term).lt.tol)go to 10

sum=sum+term

term=term*(-x**2/(2*n*(2*n+1)))

enddo

10 write(*,*)’Calculated value, Actual Value’

write(*,*)sum,sin(x)

stop

end

Page 11: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

11

Conversion of Numbers

From Decimal to Binary: (Integer)

Theory: Base 10 system -> Base 2 system. Continue downwards, dividing each new quotient by two and writing the remainders to the right of each

dividend. Stop when the quotient is 1.

For example, a decimal number, 156 (may be written as 15610 ) is converted to a binary number 10011100 (may be written as 100111002)

2)156 0

2)78 0

2)39 1

2)19 1

2)9 1

2)4 0

2)2 0

1

FORTRAN Program:

C From Decimal to Binary

C

dimension ib(100)

write(*,*)'Give a Decimal Number'

read(*,*)n

do i=1,100

if(n.le.1)then

ib(i)= n

go to 10

endif

ib(i)= mod(n,2)

n=n/2

enddo

10 write(*,*)'The Binary Number’

write(*,*)(ib(k),k=i,1,-1) ! Implied do-loop

stop

end

Algorithm: (For Integer Numbers)

1. Input: a number (integer)

2. Divide by 2 (Modulo)

3. Store the remainder in memory.

4. Take the Quotient for the next step.

5. Repeat steps 2 & 3 until the Quotient is 1 or 0.

6. When the Quotient is 1 0r 0, store this as remainder.

7. Write the stored remainders (either 0 or 1) in reverse order

Page 12: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

12

C From Decimal to Binary

C

dimension ib(100), ibc(100)

write(*,*)'Give a Decimal Number'

read(*,*)x

intx=x ! Integer part

fracx=x-intx ! Fractional part

do i=1,1000 ! Loop for Integer part

if(intx.le.1)then

ib(i)=intx

go to 10

endif

ib(i)= mod(intx,2)

intx=intx/2

enddo

10 do j=1,1000 ! Loop for Fractional part

fracx=fracx*2

ibc(j)=fracx

fracx=fracx-ibc(j)

if(fracx.eq.0.0.or.j.eq.8)go to 20

enddo

20 write(*,*)'Binary Number = ',

(ib(k),k=i,1,-1),'.',(ibc(k),k=1,j)

stop

end

Decimal to Binary (For Real Numbers, fractional part considered):

Theory:

For the conversion of fractional part, we have to multiply by 2 and collect the real part of the

product.

Algorithm:

1. Input: a number (real number)

2. Take the integer part. Divide by 2

3. Store the remainder in memory.

4. Take the Quotient for the next step.

5. Repeat steps 3 & 4 until the

Quotient is 1 or 0.

6. When the Quotient is 1 or 0, store

this as remainder.

7. Write the stored remainders (either

0 or 1) in reverse order.

8. Now take the fractional part,

multiply by 2, store the integer part

of real number obtained.

9. Subtract the above integer from the

new real number and obtain a new

fraction.

10. Repeat the steps from 8-10 until the

fraction becomes 0 or stop after

some steps for recurring fraction.

11. Write the integers

Page 13: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

13

From Decimal to Octal:

Theory: Base 10 system -> Base 8 system. We have to divide by 8 and we stop when the quotient is less than 8. The octal (base 8) numeral system has 7 possible values, represented as 0, 1, 2, 3, 4, 5, 6 and 7 for each place-value. Continue downwards, dividing each new quotient by 8 and store the remainders. Stop when the quotient is less than 8. For example, a decimal number, 156 (may be written as 15610 ) is converted to a Octal number 234 (may be written as 2348) 8)156 4 8)19 3 2

FORTRAN Program:

Algorithm: (For Integer Numbers)

1. Input: a number (integer)

2. Divide by 8 (Modulo)

3. Store the remainder in memory.

4. Take the Quotient for the next step.

5. Repeat steps 2 & 3 until the Quotient is less than 8.

6. When the Quotient less than 8, store this as remainder.

7. Write the stored remainders (between 0 & 7) in reverse

order

C From Decimal to Octal

C

dimension ib(100)

write(*,*)'Give a Decimal Number'

read(*,*)n

do i=1,100

if(n.le.7)then

ib(i)=n

go to 10

endif

ib(i)= mod(n,8)

n=n/8

enddo

10 write(*,*)'The Octal Number’

write(*,*)(ib(k),k=i,1,-1) ! Implied do-loop

stop

end

Page 14: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

14

Decimal to Octal (For Real Numbers, fractional part considered):

Theory:

For the conversion of fractional part, we have to multiply by 2 and collect the real part of the

product.

Algorithm:

1. Input: a number (real number)

2. Take the integer part. Divide by 8

3. Store the remainder in memory.

4. Take the Quotient for the next step.

5. Repeat steps 3 & 4 until the

Quotient is less than 8.

6. When the Quotient is less than 8,

store this as remainder.

7. Write the stored remainders

(between 0 and 7) in reverse order

8. Now take the fractional part,

multiply by 8, store the integer part

real number obtained.

9. Subtract the above integer from the

new real number and obtain a new

fraction.

10. Repeat the steps from 8-10 until the

fraction becomes 0 or stop after

some steps if recurring.

11. Write the stored integers

C From Decimal to Octal

C

Dimension io(100), ioc(100)

write(*,*)'Give a Decimal Number'

read(*,*)x

intx=x ! Integer part

fracx=x-intx ! Fractional part

do i=1,1000 ! Loop for integer part

if(intx.le.7)then

io(i)=intx

go to 30

endif

io(i)=mod(intx,8)

intx=intx/8

enddo

30 do j=1,1000 ! Loop for fractional part

fracx=fracx*8

ioc(j)=fracx

fracx=fracx-ioc(j)

if(fracx.eq.0.0.or.j.ge.8)go to 40

enddo

40 write(*,*)'Octal Number = ',

(io(k),k=i,1,-1),'.',(ioc(k),k=1,j)

stop

end

Page 15: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

15

From Binary to Decimal:

Theory:

To convert a binary number: List the powers of 2 from right to left. Start at 20, next increase the

exponent by 1 for each power. Stop when the amount of elements in the list is equal to the

amount of digits in the binary number. For example, the number 10011 has 5 digits, so the

corresponding decimal number = = 19

Algorithm:

1. Input: Binary number, total number of digits

2. Define the binary number as a ‘character’ so as to read each digit in it.

3. Find each digit of the number (either 0 or 1) and its position (n) counted from right to

left.

4. The digit (0 or 1) found from step 3 is multiplied by

5. Obtain the sum in a do-loop.

6. Write the sum which is the decimal number.

FORTRAN Program:

C

C From Binary to Decimal

C

write(*,*)'Give a Binary Number'

read(*,*)number

write(*,*)'Total Number of Digits?'

read(*,*)n

nsum=0

do i=1,n

nd=mod(number,10)

number=number/10.

nsum=nsum+nd*2**(i-1)

enddo

write(*,*)'Decimal Number = ',nsum

stop

end

Page 16: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

16

From Octal to Decimal:

Theory:

To convert a octal number: List the powers of 8 from right to left. Start at 80, next increase the

exponent by 1 for each power. Stop when the amount of elements in the list is equal to the

amount of digits in the binary number. For example, the number 234 has 3 digits, so the

corresponding decimal number = = 156

Algorithm:

1. Input: Octal number, total number of digits

2. Define the Octal number as a ‘character’ so as to read each digit in it.

3. Find each digit of the number (0, 1, 2, 3, 4, 5, 6 or 7) and its position (n) counted

from right to left.

4. The digit (0 to 7) found from step 3 is multiplied by

5. Obtain the sum in a do-loop.

6. Write the sum which is the decimal number.

FORTRAN Program:

C

C From Octal to Decimal

C

write(*,*)'Give an Octal Number'

read(*,*)number

write(*,*)'Total Number of Digits?'

read(*,*)n

nsum=0

do i=1,n

nd=mod(number,10)

number=number/10.

nsum=nsum+nd*8**(i-1)

enddo

write(*,*)'Decimal Number = ',nsum

stop

end

Page 17: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

17

Matrices

Addition of Two Matrices:

Theory: For the addition of two matrices, the rows and columns of the two matrices have to be equal.

The th element of a matrix is added with the same th element of another to obtain

the th element of the new matrix: .

Algorithm:

1. Input and output Matrix elements are stored in memory.

2. Input: Dimension of Matrices, Matrix elements

3. Do loop for two indices, i and j, loops are nested.

4. The th element of a matrix is added with the same th element of another to

obtain the th element of the new matrix: .

5. Write down the matrix elements with implied do loop.

FORTRAN Program:

C Addition of Two Matrices

C

dimension a(10,10),b(10,10),c(10,10)

write(*,*)'Rows & Columns of Matrices'

read(*,*)m,n

write(*,*)'Matrix elements of A?'

do i=1,m

read(*,*)(a(i,j),j=1,n)

enddo

write(*,*)'Matrix elements of B?'

do i=1,m

read(*,*)(b(i,j),j=1,n)

enddo

do i=1,m

do j=1,n

c(i,j)= a(i,j)+b(i,j)

enddo

enddo

Write(*,*)'The added Matrix'

do i=1,m

write(*,*)(c(i,j),j=1,n)

enddo

stop

end

Page 18: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

18

Product of Two Matrices:

Theory: ∑

, for the Product of two matrices, the number of columns of the

first matrix has to be the same as the number of rows of the 2nd matrix.

Algorithm:

1. Input and output Matrix elements are stored in memory.

2. Input: Dimensions of Matrices, Matrix elements

3. Do loop for three indices: i, j, k, loops are nested

4. Inside the k-loop, the th element of 1st matrix is multiplied with the th

element of 2nd matrix, and then sum is taken.

5. Write down the matrix elements with implied do loop.

FORTRAN Program:

C Product of Two Matrices

C

dimension a(10,10),b(10,10),c(10,10)

write(*,*)'Rows & Columns of Matrix A'

read(*,*)m,l

write(*,*)'Matrix elements of A?'

do i=1,m

read(*,*)(a(i,j),j=1,l)

enddo

write(*,*)'Rows & Columns of Matrix B'

read(*,*)l,n

write(*,*)'Matrix elements of B?'

do i=1,l

read(*,*)(b(i,j),j=1,n)

enddo

do i=1,m

do j=1,n

c(i,j)= 0.0

do k=1,l

c(i,j)= c(i,j)+a(i,k)*b(k,j)

enddo

enddo

enddo

Write(*,*)'The Product Matrix'

Do i=1,m

write(*,*)(c(i,j),j=1,n)

enddo

stop

end

Page 19: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

19

Transpose of a Matrix:

Theory: For the transpose of a matrix, the rows of the original matrix become the columns of the

transposed matrix and vice versa. So what we do is that we read the matrix elements and find

the elements of the transposed matrix:

Algorithm:

1. Matrix elements are stored in memory

2. Input: rows and columns, matrix elements

3. Do loop for i and j:

4. Transpose matrix elements written in implied do loop

FORTRAN Program:

C Transpose of a Matrix

C

dimension a(10,10),b(10,10)

write(*,*)'No. of rows and columns?'

read(*,*)m,n

write(*,*)'Matrix elements?'

do i=1,m

read(*,*)(a(i,j),j=1,n)

enddo

C

do i=1,n

do j=1,m

b(i,j)=a(j,i)

enddo

enddo

C

Write(*,*)'The Transposed Matrix'

Do i=1,n

write(*,*)(b(i,j),j=1,m)

enddo

stop

end

Page 20: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

20

Numerical Analysis

Integration by Simpson’s 1/3rd Rule:

Theory:

[See APPENDIX I for the detailed theory and calculations.]

Algorithm:

1. The function is defined in a subroutine.

2. Input: Lower limit , Upper limit

3. Calculate :

4. Evaluate: , ,

)

5. Calculate the sum: (

)

6. Multiply step 5 by

FORTRAN Program:

)(

24)(

3)( bf

bafaf

hdxxf

b

a

C Simpson’s 1/3 Rule

C

write(*,*)'Lower limit, Upper Limit’

read(*,*)a,b

h=(b-a)*0.5

x=(a+b)*0.5

sum=f(a)+4*f(x)+f(b)

s=h/3*sum

write(*,*)'Value of Integral= ', s

stop

end

C

C Subroutine for function

function f(x)

f=x**2

return

end

Page 21: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

21

Integration by Simpson’s 1/3rd Rule (Modified):

Theory: ∫

Algorithm:

1. The function is defined in a subroutine.

2. Input: Lower limit , Upper limit , sub-intervals .

3. Calculate:

4. Evaluate:

5. Do Loop over n starts. Evaluate the function: for every odd sub-interval multiply by 4,

for every even sub-interval multiply by 2 and then add all of them.

6. Finally, multiply the sum by

FORTRAN Program:

)()(...)()(2)(...)()(4)(3

2421310 nnn xfxfxfxfxfxfxfxfh

C Simpson’s 1/3 Rule (Modified)

C

write(*,*)'Lower limit, Upper Limit,sub-intervals'

read(*,*)a,b,n

h=(b-a)/n

sum=f(a)+f(b)

d=4

do k=1,n-1

x=a+k*h

sum=sum+d*f(x)

d=6-d

enddo

s=h/3*sum

write(*,*)'Value of Integral= ', s

stop

end

C

C Subroutine for function

C

function f(x)

f=x**2

return

end

Page 22: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

22

Least Square Method: Linear Fit

Theory: Slope = ∑ ∑ ∑

∑ ∑ , Intercept =

∑ ∑ ∑ ∑

∑ ∑

[See APPENDIX I for the detailed theory and calculations.]

Algorithm:

1. Input: x, y

2. Inside the Do Loop, run the sums to

evaluate: ∑ , ∑ , ∑ , ∑

3. Calculation of slope and intercept

4. Few data points generated with

obtained slope and intercept, the

straight line drawn is superposed

over the original data points.

C Least Square fit

C

open(1,file='xy.dat')

open(2,file='fit.dat')

write(*,*)'Number of Points?'

read(*,*)n

sumx=0.0

sumy=0.0

sumsqx=0.0

sumxy=0.0

write(*,*)'Give data in the form: x,y'

do i=1,n

read(*,*)x,y

write(1,*)x,y

sumx=sumx+x

sumy=sumy+y

sumsqx=sumsqx+x*x

sumxy=sumxy+x*y

enddo

deno=n*sumsqx-sumx*sumx

slope=(n*sumxy-sumx*sumy)/deno

b=(sumsqx*sumy-sumx*sumxy)/deno

write(*,*)'Slope, Intercept= ',slope,b

C

write(*,*)'Give lower and upper limits of X'

read(*,*)xmin, xmax

x=xmin

dx=(xmax-xmin)/2.0

do i=1,3

y=slope*x+b

write(2,*)x,y

x=x+dx

enddo

stop

end

Page 23: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

23

The following programs on pages 22-26 are based on solving simple first order differential

equations, basically by Euler’s scheme. Runge-Kutta method of different orders can be used

when necessary. But we avoided that here for this set of elementary programs.

Projectile Motion

Theory:

Consider a particle projected at an angle from origin ( ), with the horizontal direction being

x-axis and the vertical direction y-axis. The force on the particle, ⃗ ⃗. Components:

. For the purpose of computation, we take ; Mass,

. Projection angle, and initial speed are given. All the quantities are in arbitrary

units.

Algorithm:

1. Input: initial velocity , angle of projection . The interval of time is set.

2. Initial values: interval of time , Force components

3. Components of initial velocity: ,

4. Change in velocity components: ,

5. New velocity components: ,

6. Change in position coordinates: ,

7. New position coordinates: ,

8. Write the position coordinates in a file and then plot to see.

The trajectory of the particle projected at an angle (indicated in the figs.) and with some initial

velocity

Page 24: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

24

FORTRAN Program:

Motion under Central Force

Theory:

Consider the Central Force, and Newton’s 2nd law of motion:

. For

computational purpose, we take , . Thus we have,

. We solve for and

then therefrom derive the position. Initial values for the velocity components, and are

provided. We choose the time interval ( appropriately. All the quantities are in arbitrary

units.

C Projectile Motion of a particle

C

open(1,file='proj.dat')

write(*,*)'Angle (in degree) and initial speed?'

read(*,*)theta,v0

dt=0.01

g=980

theta=3.14/180*theta

fx=0

fy=-g

vx=v0*cos(theta)

vy=v0*sin(theta)

x=0

y=0

do while(y.gt.0.0)

dvx=fx*dt

dvy=fy*dt

vx=vx+dvx

vy=vy+dvy

dx=vx*dt

dy=vy*dt

x=x+dx

y=y+dy

write(1,*)x,y

enddo

stop

end

Page 25: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

25

Algorithm:

1. Initial position coordinates are given. Initial velocity components and are

given.

2. Time interval is chosen.

3. Components of Force:

,

4. √

5. Change in velocity components:

,

6. New velocity components: ,

7. New position coordinates: ,

8. Write the position coordinates in a file and then plot to see.

FORTRAN Program:

C Motion under a Central Force

C

open(1,file='central.dat')

dt=0.01

vx=0.0

vy=1.0

x=1.0

y=0.0

ncount=0

do i=1,10000

r2=x*x+y*y

r=sqrt(r2)

f=-1/r2

fx=x/r*f

fy=y/r*f

vx=vx+fx*dt

vy=vy+fy*dt

x=x+dt*vx

y=y+dt*vy

n=mod(i,100)

if(n.eq.0)write(1,*)x,y

enddo

stop

end

Page 26: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

26

The Elliptical path of a particle under Central Force

Harmonic Oscillator

Theory:

Consider the Oscillator equation in the form:

. For computational purpose, we

choose mass and the force constant a positive number (all in arbitrary units). The

equation is solved to obtain the velocity and therefrom we obtain the position of the particle.

Algorithm:

1. Give the initial position ( ), initial time ( ) and velocity ( ). Set the time interval .

2. Value of spring constant is chosen appropriately, usually a small positive number.

3.

4. Updating of velocity:

5. Change in position:

6. Updating of position:

7. Updating of time:

8. Write the time and position in a file and then plot to see.

Page 27: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

27

FORTRAN Program:

The Sine Curve obtained from the solution of Linear Harmonic Oscillator Equation.

**Equation for SHM [

] is solved numerically in the above with the simple Euler

scheme. One can add a damping term (proportional to velocity) and tune the parameters to

obtain well known results and phase diagrams. However, it would be interesting to play with

the parameters and gain some insight through such numeric. See APPENDIX II.

C Harmonic Oscillator

C

open(1,file='harmonic.dat')

x=0.0

t=0

v=1.0

dt=0.01

k=5

do i=1,1000

dv=-k*x*dt

v=v+dv

dx=v*dt

x=x+dx

t=t+dt

write(1,*)t,x,v

enddo

stop

end

Page 28: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

28

Real Roots by Bisection Method

Theory:

Consider an equation, . If a real root exists between[ ], we search that root by

bisecting the interval; the midpoint being . If , is the root. If not

so, we choose either [ ] or [ ]. We check whether has opposite signs at the end

points (over any of the intervals). Then we take that new interval and bisect again. Thus we

keep searching the root according to some accuracy (we call it tolerance).

Algorithm:

1. Function defined in subroutine

2. Input:

1. If , No Root. Stop

2. Else set

3. If , is the root. Stop

4. If , set . Else set: .

5. Check if | | . Root = . Stop

6. Else go to step 3

Example:

Consider the equation: . Let us find a real root in the interval, [ ].

The following is the result of the iterations that is obtained by running the program.

No. Iterations

1 11.000000

2 6.5000000

3 4.2500000

4 3.1250000

5 2.5625000

6 2.2812500

7 2.1406250

8 2.2109375

9 2.2460938

10 2.2636719

11 2.2724609

No. Iterations

12 2.2768555

13 2.2790527

14 2.2779541

15 2.2785034

16 2.2787781

17 2.2789154

18 2.2789841

19 2.2790184

20 2.2790356

21 2.2790270

Page 29: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

29

FORTRAN Program:

Newton-Raphson Method

Theory:

If we can find the derivative such that and also know that is monotonic in

[ ], we have:

Starting from an approximate value , we can generate the sequence

C Bolzano Bisection Method

write(*,*)'Lower Limit, Upper Limit, Tolerance'

read(*,*)a,b,eps

C

C Testing if the root exists in this range

C

if(f(a)*f(b).gt.0.0)then

write(*,*)'No Root'

stop

endif

C

C Bisection Loop starts

C

do while(abs(b-a).ge.eps)

xm=0.5*(a+b)

if(f(xm).eq.0.0)go to 10

if(f(a)*f(xm).lt.0.0)then

b=xm

else

a=xm

endif

enddo

10 write(*,*)'Root = ',xm

stop

end

C

function f(x)

f=x**3-3*x-5

return

end

Page 30: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

30

Algorithm:

1. Define and derivative in subroutine

2. Input: Guess value of , Tolerance, Max. no. of Iterations

3. Iteration in do loop:

4. Update:

5. Check if | | , then either or is the root. Stop.

6. Else continue until max iterations.

FORTRAN Program:

C Newton-Raphson Method

write(*,*)'Initial approx, Tolerance, Max iteration'

read(*,*)x,tol,maxit

do i=1,maxit

x0=x

x=x-f(x)/f1(x)

if(abs(x-x0).lt.tol)then

root=x

write(*,*)'Root =', root

stop

endif

if(i.eq.maxit)write(*,*)'No Solution'

enddo

stop

end

C

function f(x)

f=x**3-3*x-5

return

end

C

function f1(x)

f1=3*x**2-3

return

end

Page 31: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

31

APPENDIX I

Least Square Fit:

Theory: The following is a theory for data to be fitted with a straight line.

The equation of a straight line is bmxy

Consider the data points ( 11 , yx ) , ( 22 , yx )…….etc.

Error is defined as 2

1

)(),( ii

n

i

ybxmbm

.

For the best fit, this error should be minimum.

Therefore, 0

m

and 0

b

.

Now,

2

1

)(n

i

ii ybmxmm

= 2

1

)( ii

n

i

ybxmm

= )().(21

iiii

n

i

ybmxm

ybxm

= ii

n

i

i xybmx )(21

= i

n

i

i

n

i

i

n

i

i xyxbxm

111

222 = 0 (1)

Similarly,

n

i

i

n

i

i ynbxmb 11

0

(2)

From (1) and (2),

n

i

ii

n

i

i

n

i

i

n

i

i

n

i

i

xy

y

m

b

xx

xn

1

1

1

2

1

1

Slope,

n

i

n

i

ii

n

i

n

i

n

i

iiii

xxn

xyyxn

m

1

2

1

2

1 1 1

)(

and Intercept,

n

i

n

i

ii

n

i

n

i

n

i

iii

n

i

ii

xxn

yxxxy

b

1

2

1

2

1 1 11

2

)(

.

Example: For the data points (1,2), (2,3), (3,4), (4,5)

4n , 1043211

n

i

ix , 1454321

n

i

iy

40544332211

n

i

ii yx , 30443322111

2

n

i

ix

Page 32: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

32

120

20

100120

140160

10304

10144042

m , 1

20

20

100120

400420

10304

401030142

b .

Fig. Example of a linear least square fit

Simpson’s 1/3 Rule:

Theory: Simpson’s 1/3 rule is where the integrand is approximated by a second order polynomial.

Fig. Integration of a function

Page 33: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

33

where )(2 xf is a second order polynomial given by

. Choose

)),(,( afa ,2

,2

baf

ba and ))(,( bfb

as the three points of the function to evaluate ,0a 1a and 2a .

Solving the above three equations for unknowns, ,0a 1a and 2a give

Then

Substituting values of ,0a 1a and 2a gives

b

a

b

a

dxxfdxxfI )()( 2

2

2102 )( xaxaaxf

2

2102 )()( aaaaaafaf

2

21022222

baa

baaa

baf

baf

2

2102 )()( babaabfbf

22

22

02

)()(2

4)()(

baba

afbaabfba

abfbabfbfa

a

2212

)(2

4)(3)(32

4)(

baba

bbfba

bfabfbafba

afaaf

a

2222

)(2

2)(2

baba

bfba

faf

a

b

a

dxxfI )(2

b

a

dxxaxaa 2

210

b

a

xa

xaxa

32

3

2

2

10

32)(

33

2

22

10

aba

abaaba

Page 34: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

34

Since for Simpson 1/3 rule, the interval ba, is broken into 2 segments, the segment width

Hence the Simpson’s 1/3 rule is given by

)(

24)(

3)( bf

bafaf

hdxxf

b

a

Since the above form has 1/3 in its formula, it is called Simpson’s 1/3 rule.

Simpson’s 1/3 Rule (modified version) (Multiple-segment Simpson’s 1/3 Rule)

Theory:

For better result, one can subdivide the interval ba, into n segments and apply Simpson’s

1/3 rule repeatedly over every two segments. Note that n needs to be even. Divide

interval ba, into n equal segments, so that the segment width is given by

n

abh

.

Now

where

Apply Simpson’s 1/3rd Rule over each interval,

Since

)(

24)(

6)(2 bf

bafaf

abdxxf

b

a

2

abh

nx

x

b

a

dxxfdxxf

0

)()(

ax 0

bxn

n

n

n

n

x

x

x

x

x

x

x

x

b

a

dxxfdxxfdxxfdxxfdxxf

2

2

4

4

2

2

0

)()(......)()()(

...6

)()(4)()(

6

)()(4)()()( 432

24210

02

xfxfxfxx

xfxfxfxxdxxf

b

a

6

)()(4)()(

6

)()(4)()( 12

2

234

42

nnn

nn

nnn

nn

xfxfxfxx

xfxfxfxx

Page 35: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

35

then

APPENDIX II

Oscillations: a pictorial tour

(Results obtained from solving corresponding differential equations in computer)

hxx ii 22

ni ...,,4,2

...6

)()(4)(2

6

)()(4)(2)( 432210

xfxfxfh

xfxfxfhdxxf

b

a

6

)()(4)(2

6

)()(4)(2 12234 nnnnnn xfxfxf

hxfxfxf

h

)()(...)()(2)(...)()(4)(3

2421310 nnn xfxfxfxfxfxfxfxfh

𝑑 𝑋

𝑑𝑡 𝑘 𝑋

Simple Harmonic Motion

(No damping)

Page 36: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

36

𝑑 𝑋

𝑑𝑡 𝜆

𝑑𝑋

𝑑𝑡 𝑘 𝑋

Damped Harmonic Motion

(Critical Damping)

Damped Harmonic Motion

(Large damping)

Page 37: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

37

Damped Harmonic Motion

(Small damping)

𝑑 𝑋

𝑑𝑡 𝜆 𝑋

𝑑𝑋

𝑑𝑡 𝑘 𝑋

Relaxation Oscillation

Van der Pol Oscillator:

Page 38: FORTRAN Programs for Physics Students

Dr. Abhijit Kar Gupta, Deptt. Physics, PBC, [email protected] 2014

38

This set of programs is intended to be distributed among physics students (U.G. and P.G.) for their

coursework in Computation.

FORTRAN Programs for Physics Students (with Theory and Algorithms)

Abhijit Kar Gupta

Department of Physics, Panskura Banamali College

Panskura R.S., East Midnapore, West Bengal, India, Pin Code: 721152

e-mail: [email protected]