START GET THE SOURCE ADDRESS, DESTINATION · PDF file · 2017-04-19Microprocessor...
Transcript of START GET THE SOURCE ADDRESS, DESTINATION · PDF file · 2017-04-19Microprocessor...
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 1
Microprocessor 8085 – Programs Block Move, addition, subtraction operations. Aim: (A) To move a block of data bytes from the given source address to the destination address (B) To perform basic arithmetic (Addition and Subtraction) operations. (C) To perform basic Logical (AND, OR, NOT, XOR Operations)
A. Block Move Flow chart
GET THE SOURCE ADDRESS,
DESTINATION ADDRESS AND
NO.OF BYTES TO MOVE
COPY BYTE FROM THE LOCATION POINTED TO
BY THE SRC POINTER TO THE LOCATION
POINTED TO BY THE DEST POINTER
INCREMENT THE SRC POINTER AND DEST
POINTER BY ONE. DECRERMENT THE COUNTER
BY ONE
IS COUNTER
= 0 ?
STOP
START
INITIALIZE MEMORY POINTERS TO
SOURCE, DEST ADDRESSES AND A
COUNTER
NO
YES
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 2
Block Move - Program
To copy 10 bytes starting from source address 8600 to the destination address 8700 onwards.
Label Mnemonics Address Opcode Byte1
Operand Byte2
Operand Byte3
Comment
START: LXI H,8600 8500 ; (HL) <- SRC ADDRESS
LXI D,8700 ;(DL) <- DEST ADDRESS
MVI C,0A ; (C) <- COUNT (10)
REPEAT: MOV A,M ; (A) <- (SRCPTR)
STAX D ;(DESTPTR) <- (A)
INX H ; SRCPTR <- SRCPTR +1
INX D ;DESTPTR <- DESTPTR+1
DEC C ;COUNT <- COUNT-1
JNZ REPEAT ;IF COUNT !=0 REPEAT
STOP: HLT/RST1
RESULT:
The block move (copy) operation is performed and the locations are verified.
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 3
ADDITION
i) Addition of two 8 bit numbers
GET THE BYTE1 IN ACC AND
BYTE 2 IN B REG. USING ANY
ONE OF THE ADDRESSING
MODE
(ACC) (ACC) + (B)
IS CARRY ?
STOP
START
CLEAR ACCUMULATOR, D REG.
AND CARRY FLAG
(D) 1
STORE SUM (A) IN
MEM.LOCATION AND
CARRY (D) IN
MEM.LOC+1
NO
Yes
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 4
a. IMMEDIATE ADDRESSING MODE
Label Mnemonics Address Opcode Byte1
Operand Byte2
Operand Byte3
Comment
START: XRA A 8500 ; (A) <- 0, CY <-0
MVI D,0 ;(D) <- 0
MVI A, BYTE1 ; (A) <- number1
MVI B, BYTE2 ; (B) <- number2
ADD B ;(A) <- (A)+(B)
JNC STORE ; IF NO CARRY JUMP TO STORE
INR D ;CARRY<-1
STORE: STA 8600 ;STORE ACC
MOV A,D ; GET CARRY IN ACC
STA 8601 ;STORE CARRY
STOP: HLT/RST 1
RESULT
Address Value 8600 Sum
8601 Carry
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 5
b. DIRECT ADDRESSING MODE
Label Mnemonics Address Opcode Byte1
Operand Byte2
Operand Byte3
Comment
START: XRA A 8500 ;(A) <- 0, CY <-0
MVI D,0 ;(D) <- 0
LDA 8600 ; (A) <- (8600)
MOV B,A ; (B) <- (A)
LDA 8601 ;(A) <- (8601)
ADD B ;(A) (A) + (B)
JNC SKIP ; IF CY=0 THEN SKIP
INR
INR D ;(D) (D) +1
SKIP: STA 8602 ;STORE SUM
MOV A,D ;MOVE CARRY TO A
STA 8603 ;STORE CARRY
STOP: HLT
RESULT
Address Value Remark Input
8600 Data1
8601 Data2 Output
8602 Sum
8603 Carry
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 6
c. INDIRECT ADDRESSING MODE
Label Mnemonics Address Opcode Byte1
Operand Byte2
Operand Byte3
Comment
START: XRA A 8500 ; (A) <- 0, CY <-0
MVI D,0 ;(D) <- 0
LXI H,8600 ; Initialize Memory Ptr. to point first number
MOV A,M ; (A) <- number1
INX H ; Increment Memory Ptr. to pt. next number
MOV B ,M ; (B) <- number2
ADD B ;(A) <- (A)+(B)
JNC SKIP ; If No Carry Jump To Store
INR D ;
STORE: STA 8600 ;Store Acc
MOV A,D ; Get Carry In Acc
STA 8601 ;Store Carry
STOP: HLT
RESULT
Address Value Remark Input
8600 Data1
8601 Data2
Output
8602 Sum
8603 Carry
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 7
d. ADDITION - SUM OF TWO 16 BIT NUMBERS
Label Mnemonics Address Opcode Byte1
Operand Byte2
Operand Byte3
Comment
START: XRA A 8500 ; (A) <- 0, CY <-0
MVI C,0 ;(C) <- 0
LHLD 8600 ;(L) <- LB of number1 ;(H) <- HB of number1
XCHG ; (E) <- LB of number1 ; (D) <- HB of number1
LHLD 8602 ;(L) <- LB of number2 ;(H) <- HB of number2
DAD D ; (HL) <-(HL)+(DE)
JNC SKIP ; IF NO CARRY JUMP TO STORE
INR C ;
STORE: SHLD 8604 ;STORE 16 BIT SUM ;(8604)<- LB of Sum ;(8605) <- HB of Sum
MOV A,C ; GET CARRY IN ACC
STA 8606 ;STORE CARRY
STOP: HLT
Address Value Remarks Input
8600 Lower order Byte1
8601 Higher order Byte1
8602 Lower order Byte2
8603 Higher order Byte2
Output
8604 LB of Sum
8605 HB of Sum
8606 Carry
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 8
SUBTRACTION - IMMEDIATE ADDRESSING MODE
Label Mnemonics Address Opcode Byte1
Operand Byte2
Operand Byte3
Comment
MVI A, BYTE1 ; (A) <- number1
MVI B, BYTE2 ; (B) <- number2
SUB B ;(A) <- (A)-(B)
STORE: STA 8600 ;STORE DIFFERENCE
STOP: HLT
RESULT
Address Value Remark 8600
SUBTRACTION – DIRECT ADDRESSING MODE
Label Mnemonics Address Opcode Byte1
Operand Byte2
Operand Byte3
Comment
START: LDA 8600 ; (A) <- (8600) MOV B,A ; (B) <- (A) LDA 8601 ;(A) <- (8601) SUB B ;(A) (A) - (B) STA 8602 ;STORE DIFFERENCE STOP: HLT
RESULT
Address Value Remark Address Value Remark
Input Input
8600 4E Data1 8600 25 Data1
8601 5F Data2 8601 13 Data2
Output Output
8602 Difference 8602 Difference
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 9
SUBTRACTION - INDIRECT ADDRESSING MODE
Label Mnemonics Address Opcode Byte1
Operand Byte2
Operand Byte3
Comment
START: LXI H,8600 ; Initialize Memory Ptr. to point first number
MOV A,M ; (A) <- number1
INX H ; Increment Memory Ptr. to pt. next number
MOV B ,M ; (B) <- number2
SUB B ;(A) <- (A)-(B)
STORE: STA 8600 ;STORE DIFFERENCE
STOP: HLT
RESULT
Address Value Remarks Input 8600 Data1
8601 Data2
Output
8602 Difference
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 10
16 BIT SUBTRACTION
Label Mnemonics Address Opcode Byte1
Operand Byte2
Operand Byte3
Comment
START: LHLD 8600 ;(L) <- LB of number1 ;(H) <- HB of number1
MOV C,L ; (C) <- LB of number1
MOV B,H ;(B) <- LB of number1
LHLD 8602 ;
DSUB B 0B ;(HL) (HL)- (BC)
STORE: SHLD 8604 ;STORE DIFF ;(8604)<- LB of Diff ;(8605) <- HB of Diff
STOP: HLT
RESULT
Address Value Remarks Input
8600 Lower order Byte1
8601 Higher order Byte1
8602 Lower order Byte2
8603 Higher order Byte2
Output
8604 LB of Difference
8605 HB of Difference
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 11
C) Logical Operartions
i) AND operation data1 = 25H , data2 = A2H
Label Mnemonics Address Opcode Byte1
Operand Byte2
Operand Byte3
Comment
START: MVI A, data1 ;(A) data1 MVI B, data2 ; (B) data2 ANA B ;(A) (A) (B) STA 8600 ; (8600) Result
STOP: HLT
ii) OR operation
Label Mnemonics Address Opcode Byte1
Operand Byte2
Operand Byte3
Comment
START: MVI A, data1 ;(A) data1 MVI B, data2 ; (B) data2 ORA B ;(A) (A) (B) STA 8600 ; (8600) Result
STOP: HLT
iii) XOR operation
Label Mnemonics Address Opcode Byte1
Operand Byte2
Operand Byte3
Comment
START: MVI A, data1 ;(A) data1 MVI B, data2 ; (B) data2 XRA B ;(A) (A) (B) STA 8600 ; (8600) Result
STOP: HLT
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 12
iv) NOT operation
Label Mnemonics Address Opcode Byte1
Operand Byte2
Operand Byte3
Comment
START: MVI A, data1 ;(A) data1 CMA ; (A) (A)’ STA 8600 ; (8600) Result
STOP: HLT
Result
Sno Data1 Data2 Data1 AND Data2
Data1 OR Data2
Data1 XOR Data2
NOT Data1
1
2
3
4
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 13
Multiplication and Division
8 Bit Multiplication - Using successive Addition (i) 17h x 29h (ii) F2 x A5
GET THE MULTIPLICAND IN B
REG. AND MULTIPLIER IN C REG.
USING ANY ONE OF THE
ADDRESSING MODE
(ACC) (ACC) + (B)
IS CARRY ?
STOP
START
CLEAR ACCUMULATOR, D REG.
AND CARRY FLAG
(D)(D)+ 1
STORE PRODUCT (16bit)
IN MEM.LOCATION AND
CARRY IN MEM.LOC+1
IS (C) = 0?
(C)(C) - 1
Yes
No
Yes
No
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 14
Label Mnemonics Address Opcode Byte1
Operand Byte2
Operand Byte3
Comment
START: XRA A 8500 ; (A) <- 0, CY <-0
MVI D,00 ;(D) <- 0
LXI H,8600 ; Initialize Memory Ptr. to point multiplicand
MOV B,M ; (B) <- Multiplicand
INX H ; Increment Memory Ptr. to pt. multiplier
MOV C ,M ; (C) <- multiplier
REPEAT: ADD B ;(A) <- (A)+(B)
JNC DECR ; IF NO CARRY JUMP TO DECR
INR D ;(D) <- (D) + 1
DECR: DEC C ;(C) <- (C) -1
JNZ REPEAT ;IF C!=0 THEN REPEAT
STORE: INX H ;INCR. MEM.PTR
MOV M,A ; STORE PRODUCT (LB)
INX H ;INCR.MEM.PTR
MOV M,D ;STORE PRODUCT (HB)
STOP: HLT ;STOP
Result:
(i) (ii)
Address Value Remarks Value Remarks 8600
Multiplicand Multiplicand
8601
Multiplier Multiplier
8602
Product (LB) Product (LB)
8603
Product (HB) Product (HB)
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 15
Multiplication of 16 Bit and 8 Bit Numbers (i) 4F12 x 25 (ii) F12A x F5
Label Mnemonics Address Opcode Byte1
Operand Byte2
Operand Byte3
Comment
START: XRA A 8500 ; (A) <- 0, CY <-0
MVI B,00 ;(B) <- 0
LDA 8600 ;(A) <- 8 BIT MULTIPLIER
MOV C,A
; (C) <-MULTIPLIER
LHLD 8601 ;(L) <- LB of MULTIPLICAND ;(H) <- HB of “
XCHG (DE) <- MULTIPLICAND
LXI H,0000 ;(HL)<- 0000 (ACC<-00)
REPEAT: DAD D ; (HL) <-(HL)+(DE)
JNC DECR ; IF NO CY JUMP TO DECR
INR B ; Carry Carry +1
DECR: DCR C
; (C ) (C) -1
JNZ REPEAT
;IF C!=0 THEN REPEAT
STORE: SHLD 8603 ;STORE 16 BIT SUM ;(8603)<- LB of Sum ;(8604) <- HB of Sum
MOV A,B ; GET CARRY IN ACC
STA 8606 ;STORE CARRY
STOP: HLT
Result
Address Value Remarks Value Remarks 8600 8 BIT multiplier 8 BIT multiplier
8601 LB of Multiplicand LB of Multiplicand
8602 HB of Multiplicand HB of Multiplicand
8603 LB of Product LB of Product
8604 HB of Product HB of Product
8605 Carry Carry
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 16
8 Bit Division - Using Repeated Subtraction (i) 6A ÷ 12H (ii) 25 ÷ 1A
GET THE DIVIDEND IN A REG.
AND DIVISOR IN B REG. USING
ANY ONE OF THE ADDRESSING
MODE
(A) (A) - (B)
IS CARRY ?
STOP
START
CLEAR ACCUMULATOR, D REG.,
AND CARRY FLAG
(D)(D)+ 1
STORE QUOTIENT (D)
IN MEM.LOCATION AND
REMAINDER IN
MEM.LOC+1
(A)(A) + (B)
(Restore A value)
No
Yes [A<B]
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 17
Label Mnemonics Address Opcode Byte1
Operand Byte2
Operand Byte3
Comment
START: XRA A 8500 ; (A) <- 0, CY <-0
MVI D,0 ;(D) <- 0
LXI H,8600 ; Initialize Memory Ptr. to point Dividend
MOV A,M ; (A) <- Dividend
INX H ; Increment Memory Ptr. to pt. Divisor
MOV B ,M ; (C) <- multiplier
REPEAT: SUB B ;(A) <- (A)-(B)
JC RESTORE ; IF CARRY JUMP TO RESTORE (A) value
INR D ;(D) <- (D) + 1
JMP REPEAT ;JUMP TO SUBTRACT
RESTORE: ADD B ;RESTORE ACC. VALUE
INX H ;INCR. MEM.PTR
STORE: MOV M,A ; STORE REMAINDER
INX H ;INCR.MEM.PTR
MOV M,D ;STORE QUOTIENT
STOP: HLT
;STOP
Result
Address Value Remarks Value Remarks 8600
Dividend
Dividend
8601
Divisor
Divisor
8602
Remainder
Remainder
8603
Quotient
Quotient
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 18
MINIMUM AND MAXIMUM VALUE IN A LIST OF N - NUMBERS
MOVE THE NO. OF ELEMENTS TO C REG. AND INCEMENT MEM.PTR TO POINT
THE FIRST DATA ELEMENT
IS (A) > (M)?
STOP
START
CLEAR ACCUMULATOR AND CARRY FLAG.
LET (A) 0, THE BIG
(A)(M)
STORE BIGGEST NUM ,(A)
IN MEM.LOCATION
INITIALIZE MEMORY
POINTER TO POINT THE
ARRARY
IS C = 0 ?
(C) (C) - 1
Y
N
Y
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 19
Maximum value in a list
Label Mnemonics Address Opcode Byte1
Operand Byte2
Operand Byte3
Comment
START: XRA A 8500 ; (A) <- 0, CY <-0 ; (A) : THE BIGGEST
LXI H,8600 ; INITIALIZE MEMORY PTR. TO POINT THE ARRAY
MOV C,M ; (C) <- COUNT
INX H ; INCREMENT MEMORY PTR. TO PT. FIRST ELEMENT
REPEAT: CMP M ;(A) ~ (M)
JNC NEXT
; IF (A)> (M) JUMP TO NEXT ELEMENT
MOV A,M ;(A) <- (M) (big)
NEXT: INX H ;INCR. PTR TO NEXT ELEMENT
DCR C ;COUNT <- COUNT -1
JNZ REPEAT ;IF COUNT !=0
COMP.NEXT ELEMENT
STORE: MOV M,A ; STORE THE BIG
STOP: HLT ;STOP
Note: The biggest item is stored next to the last input item in memory
Address Value Remarks 8600 COUNT 8601 DATA1 8602 DATA2 8603 DATA3 8604 DATA .N 8XXX BIGGEST NUM
RESULT
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 20
MINIMUM value in a list
Label Mnemonics Address Opcode Byte1
Operand Byte2
Operand Byte3
Comment
START: XRA A 8500 ; (A) <- 0, CY <-0 ; (A) : THE SMALLEST
LXI H,8600 ; INITIALIZE MEMORY PTR. TO POINT THE ARRAY
MOV C,M ; (C) <- COUNT
INX H ; INCREMENT MEMORY PTR. TO PT. FIRST ELEMENT
REPEAT: CMP M ;(A) ~ (M)
JC NEXT ; IF (A)< (M) JUMP TO NEXT ELEMENT
MOV A,M ;(A) <- (M) (small)
NEXT: INX H ;INCR. PTR TO NEXT ELEMENT
DCR C ;COUNT <- COUNT -1
JNZ REPEAT ;IF COUNT !=0
COMP.NEXT ELEMENT
STORE: MOV M,A ; STORE THE
SMALLEST
STOP: HLT ;STOP
Address Value Remarks 8600 COUNT 8601 DATA1 8602 DATA2 8603 DATA3 8604 8XXX SMALLEST NUM
RESULT:
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 21
SEARCH THE GIVEN ITEM IN A LIST
MOVE THE NO. OF ELEMENTS TO C REG. AND INCEMENT MEM.PTR TO POINT THE SEARCH ITEM
GET THE SEARCH ITEM IN ACC AND INCREMENT THE MEM.PTR
IS (A) = (M)?
STOP
START
CLEAR ACCUMULATOR AND CARRY FLAG.
LET (D) 0, SEARCH COUNT
ITEM FOUND
(D)(D)+1
STORE (D) - NUM OF
OCCURANCES
INITIALIZE MEMORY POINTER TO
POINT THE ARRARY
IS C = 0 ?
(C) (C) - 1
N
Y
Y
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 22
Label Mnemonics Address Opcode Byte1
Operand Byte2
Operand Byte3
Comment
START: XRA A 8500 ; (A) <- 0, CY <-0
LXI H,8600 ; INITIALIZE MEMORY PTR. TO POINT THE ARRAY
MOV C,M ; (C) <- COUNT
INX H ; INCREMENT MEMORY PTR. TO PT. SEARCH ITEM
MOV A,M ; GET THE SEARCH ITEM IN ACC.
INX H ; INR.MEM PTR. TO PT. FIRST DATA ELEMENT
REPEAT: CMP M ;(A) ~ (M)
JNZ NEXT
; IF (A)!= (M) JUMP TO NEXT ELEMENT
INR D ;ITEM FOUND ;OCCURANCE <- OCCURANCE +1
NEXT: INX H ;INCR. PTR TO NEXT ELEMENT
DCR C ; COUNT <- COUNT-1
JNZ REPEAT ;IF COUNT !=0
COMP.NEXT ELEMENT
STORE: MOV M,D ; STORE OCCURANCE
STOP: HLT ;STOP
RESULT
Address Value Remarks 8600 N – NO.OF ELEMENTS
8601 SEARCH ITEM
8602 DATA1
8603 DATA2
8604
8XXX DATA N
8XXX RESULT
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 23
Sorting the given list of numbers in ascending /in descending order
Aim : To arrange the given set of data elements in ascending or descending order.
Sorting Algorithm (Bubble sort)
i. Initialize array ( store the elements from 8601 to 86NN, NN → No. of elements)
ii. Initialize (BC) 86NN
iii. Initialize (HL) 86NN
iv. for i = (C) to 1 ; For I = N to 1
v. for j = I to 1
vi. (A) Mem[BC]
vii. IF (A) > (M)
viii. Swap Mem(BC) and Mem(HL)
ix. End if
x. next j (j j-1)
xi. next i (i i-1)
xii. End
Draw the Flowchart based on the Algorithm
Program (Ascending order)
LABEL MNEMONICS ADDRESS OPCODE
COMMENT BYTE1 BYTE2 BYTE3
START: LXI B,8605 8500 MOV H,B 8503 LOOP1: MOV L,C 8504 LOOP2: LDAX B 8505 CMP M 8506 JNC SKIP 8507 SWAP: MOV D,M 850A MOV M,A 850B MOV A,D 850C STAX B 850D SKIP: DCR L 850E JNZ LOOP2 850F DCR C 8512 JNZ LOOP1 8513 END: HLT 8516
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 24
Given data: 33 , 22, 66, 11 , 88
Store the data from 8601 on wards
8601 33 11 8602 22 22 8603 66 33 8604 11 66 8605 88 88
The last location is 8605, which is used to initialize the BC and HL pair. The lower byte in the
last address of the data is the number of items or the array size.
Modify the program to arrange the numbers in descending order.
Given data
Sorted data
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 25
Series Generation: (a) Fibonacci sequence Aim : To generate the Fibonacci sequence 0,1,2,3,5,8,13,21…..
The Fibonacci sequence is a series of numberswhere a number is found by adding up the
twonumbers before it. Starting with 0 and 1, thesequence goes 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, and so
forth. Written as a rule, the expression is xn = xn-1 + xn-2.
Algorithm
i. Store T1 (00) in 8600 ii. Store T2 (01) in 8601
iii. Set (HL) to Point T1 iv. Set (BC) to Point T2 v. Initialize counter (D) N (No.of terms to be generated)
vi. (A) ((BC)) Load A indirectly via BC pair (A) T2 vii. (A) (A) + (M) T3 T2 + T1
viii. (BC) (BC)+1 ix. (HL) (HL)+1 x. Store (A) in Mem. Pointed to by (BC) (store T3)
xi. Decrement Counter D xii. If (D) not equal to zero goto step vi
xiii. End
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 26
FLOWCHART
(A) [(BC)] T3 T1+T2: (A) (A)+ (M)
(BC) (BC) +1 T3 is stored in Memory [(BC)] (A)
STOP
START
IS (D) = 0?
(D)(D) - 1
T1: (HL) points to First element 0 in 8600
T2: (BC) points to Second element 1 in 8601
(D) 10 ; Count is stored in D
(HL) (HL)+1
(M points to T2, (ie) T1 for next iteration
(BC) points to T3 (ie) T2 for next iteration
NO
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 27
Program
LABEL MENOMICS ADDRESS OPCODE BYTE1
OPERAND BYTE2
OPERAND BYTE3
COMMENT
START: LXI H,8600 8500 LXI B,8601 8503 MVI D,0A 8506 (D) <- Count 0A LOOP: LDAX B 8508 ADD M 8509 INX B 850A STAX B 850B INX H 850C DCR D 850D JNZ LOOP 850E END: HLT 8511
Result: The Fibonacci sequence (N – terms) is generated and is stored in memory
8600 00 8601 01 8602 01 8603 02 8604 03 8605 05 8606 08 8607 0D 8608 15 8609 ?
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 28
Series Generation: (b) Tribonacci sequence The tribonacci numbers are like the Fibonacci numbers, but instead of starting with two predetermined terms, the sequence starts with three predetermined terms and each term afterwards is the sum of the preceding three terms. Aim : To generate the Tribonacci sequence 0,1,1,2,4 ,7,13,24….. T(≤FF)
i. Store T1 (00) in 8600 ii. Store T2 (01) in 8601
iii. Store T3 (01) in 8602 iv. (HL) Points to T1 v. (BC) Points to T2
vi. (DE) Points to T3 vii. (A) ((BC)) Load A indirectly via BC pair (A) T2
viii. (A) (A) + (M) T3 T2 + T1 ix. (DE) (HL) x. (A) (A) + (M)
xi. (DE) (HL) xii. (BC) (BC)+1
xiii. (HL) (HL)+1 xiv. (DE) (DE)+1 xv. Store (A) in Mem. Pointed to by (BC) (store T4)
xvi. If (A) < FF go to step vii xvii. End
Draw the Flow chart
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 29
Program : Tribonacci sequence
START: 8500 LXI H,8600 21 00 86 8503 LXI B,8601 01 01 86 8506 LXI D,8602 11 02 86 LOOP: 8509 LDAX B 0A 850A ADD M 86 850B XCHG EB 850C ADD M 86 850D XCHG EB 850E INX D 13 850F STAX D 12 8510 INX H 23 8511 INX B 03 8512 CPI FF FE FF 8514 JC LOOP C2 09 85 END: 8517 HLT 76
Result: The Tribonacci sequence is generated and is stored in memory
8600 00 8601 01 8602 02 8603 03 8604 06 8605 0B 8606 14 8607 8608
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 30
C++ Programming Problems
1. Solution of Transcendental Equations using Newton Raphson Method.
An equation of the type f(x) = 0, is either algebraic or transcendental.
An equation which contains only algebraic terms is known as Algebraic equation.
E.g . 2x = 5, x2+x =1 , x7 = x(1+2x)
Transcendental equations are equations containing trigonometric, algebraic, exponential,
logarithmic, etc. terms.
2x + Sin (x)= 0, tan(x) = x , exp(x)/2+ x= 0
As analytic solutions are often either too cumbersome or simply do not exist, we need to find an
approximate method of solution. This is where numerical analysis comes into the picture.
Newton Raphson Method
The Newton-Raphson method uses an iterative process to approach one root of a function. The
specific root that the process locates depends on the initial, arbitrarily chosen x-value.
𝑥𝑛+1 = 𝑥𝑛 −𝑓(𝑥𝑛)
𝑓′(𝑥𝑛)
Here, xn is the current known x-value,
f(xn) represents the value of the function at xn,
f ’(xn) is the derivative (slope) at xn.
xn+1 represents the next x-value to find.
Essentially, f '(x), the derivative represents f(x)/dx (dx = delta-x). Therefore, the term f(x)/f '(x)
represents a value of dx.
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 31
Flow Chart
Get X0 and No.of Iterations (Nit)
X1= X0- F(X0)/F’(X0)
If |F(x)|< 0.001
STOP
START
Define F(x) and F’(x)
NO
YES
Print X0,X1,F(x) and F’(x)
X0 = X1
Print the Root. X1
Yes
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 32
Program: // Newton Raphson method of finding solution to a polynomial // Program name: ________________ #include <iostream.h> #include <conio.h> #include <math.h> #include <iomanip.h> // class defintion class Newton { private: float x0 , x1; float fx, dfx; int nit; public: Newton(float iv,int ni) // iv <- initial value, ni<- no. of iterations. { x0 = iv, nit = ni; } float fun(float x) // defintion of the polynomial equation { return x*x-25.0; } float dfun( float x) // defintion of the derivative of the polynomial { return 2*x; } void PrintSolution(); }; // definition of the function PrintSolution() void Newton:: PrintSolution() { int converge=0; clrscr(); cout<<"\n Newton Raphson Method"; cout<<"\n ------------------------------------------------"; cout<<"\n Itn x0 f(x0) df(x0) x1"; cout<<"\n ------------------------------------------------"; cout.precision(4); cout.setf(ios::showpoint); for (int i=1;i<=nit;i++) { fx = fun(x0); dfx = dfun(x0); x1 = x0 - fx/dfx; cout<<"\n " << setw(3)<<i << setw(10)<< x0 << setw(10)<<fx<< setw(10)<<dfx<< setw(10)<<x1;
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 33
if(fabs(fx) <= 0.001) { converge=1; break; } x0=x1; } // for loop ends cout<<"\n-------------------------------------------------------"; // check for convergence if(converge) cout<<" \n Root Converges. The solution is : X= " << x1; else cout<<"\n Root does not converge in "<<nit<< " Iterations"; } // Main Function void main() { float x0; int n; clrscr(); cout<<"\n Enter Initial approximation x0 :"; cin >>x0; cout<<"\n Enter No. of Iterations n :"; cin >>n; Newton N(x0,n); N.PrintSolution(); getch(); } Result: 1. Solution by analytical Method: 2. Solution by Newton Raphson Method (Manual calculation): 3. Solution by the C++ Progam : Attach Program output
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 34
2. Solution to first order Ordinary Differential Equations
dy/dx = f(x,y) with initial condition, y(x0) = y0 Eulers' Method Y1= y0+ h f(x0, y0) t1= x0+h Runge Kutta 4th Order Method
y1 = y0+ 1/6(k1+2*(k2+k3)+k4) x1= x0+h Where k1= hf(x0,y0) k2= hf(x0+h/2, y0+1/2 k1) k3= hf(x0+h/2, y0+1/2 k2); k4= hf(x0+h, y0+k3) I. Radioactive decay problem Radioactive decay, also known as nuclear decay or radioactivity: It is the spontaneous process by which a nucleus of an unstable atom loses energy by emitting radiation. The radiation released is in the form of alpha particles, beta particles, gamma rays and other particles.
Time-variable quantities
Half Life T1/2
The half-life of a radioactive substance is a characteristic constant. It measures the time it takes for a given amount of the substance to become reduced by half as a consequence of decay (by emitting radiation). For example, the half life period of Tritium is 12.3 years. If 100 g of tritiuim is in hand today, after
12.3 years 50 g of tritium will be gone (ie) decayed into helium and only 50 g will be left.
Element Half Life Carbon-14 5730 year Uranium-235 >700 million years Nitrogen less than 10 minutes Radon-224 55 sec.
Exponential Radioactive
decay process
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 35
Decay Constant or Disintegration Constant (λ) The probability that a number of nuclei will decay / sec. Unit is sec-1
λ = 0.693/ Half-life; The time constant τ = 1/λ Activity (A) The activity of a sample is the average number of disintegrations / sec. (ie) Number of decays / unit time. Unit : Bq (bequerel) Activity A = ΔN/ Δt ΔN - change in number of undecayed nuclei Δt - change in time in sec Activity A = ΔN/ Δt = -λN
Exponential Law of Radioactivity
The number of atoms disintegrated per second at any instant is directly proportional to the
number of radioactive atoms actually present in the sample at that instant.
If No be the total number of atoms at t = 0, N be the total number of atoms left in the sample at
time t then dN/dt will be the rate of disintegration.
- dN/dt N - dN/dt = λ N -dN/N = λ dt
The solution to this first-order differential equation is given by Radioactive problem by Euler's Method - Algorithm 1. define Function f (x,y) 2. input x0,y0 x0 time t0 and y0 is the ini.no. of nuclei 3. input step size,and the number of steps. 4. for i = 1 to n do y1= y0+ hf(x0,y0) x1= x0+h print x1,y1 y0 = y1; x0 = x1; next
dN/dt = - λN
N(t) = N0.exp(- λ *t)
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 36
FlowChart
Get Initial values X0 and Y0, Step size (h) and No. of Steps
STOP
START
Define F(x,y)
Print X1,Y1
Print the final values Xn, Yn
For I = 1 to No.of Steps
y1= y0+ hf(x0,y0) x1= x0+h
y1= y0 ; x1= x0+h
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 37
Program // Euler method #include <iostream.h> #include <math.h> #include <conio.h> #include <fstream.h> class RDecay { private: float N0,lamda,dt,endtime; public: RDecay(float n0, float halflife,float tstep,float et) { N0=n0; lamda= 0.693/halflife; dt=tstep; endtime= et; } float decay(float t,float N) { float dNbydt; dNbydt = -N*lamda; return dNbydt; } void EulerMethod(); }; void RDecay::EulerMethod() { float N[500],time[500]; float t,Nu; int nsteps,i=0; ofstream fout("c:\\tc\\bin\\RDEuler.dat"); nsteps= (int) (endtime/dt); cout.precision(4); cout.setf(ios::showpoint); time[0]= 0; N[0]= N0; cout<<"\n"<<setw(4)<<i<<setw(10)<<time[i]<<setw(10)<<N[i]; fout<<"\n"<<setw(4)<<i<<setw(10)<<time[i]<<setw(10)<<N[i];
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 38
for (i=1;i<=nsteps;i++) { t = time[i-1]; // current time x0 Nu = N[i-1]; // current concentration y0 N[i]= Nu+ dt*decay(t,Nu); // y1 = y0+ h f(x0,y0) time[i]=time[i-1]+dt; cout<<"\n"<<setw(4)<<i<<setw(10)<<time[i]<<setw(10)<<N[i]; fout<<"\n"<<setw(4)<<i<<setw(10)<<time[i]<<setw(10)<<N[i]; } fout.close(); getch(); } void main() { float N0,halflife,dt,tmax; cout<<"\n Enter the following inputs"; cout<<"\n Initial Number of Nuclei :" ; cin >>N0; cout<<"\n Half Life Period :" ; cin>>halflife; cout<<"\n Time step (days): :"; cin>>dt; cout<<"\n End Time (days) :"; cin>>tmax; RDecay Rd(N0,halflife,dt,tmax); Rd.EulerMethod(); cout<<"\n Result is in the file c:\\tc\\bin\\RDEuler.dat” ; getch(); } Note: plot a graph in Excel using the generated data which is available in the file RDEuler.data and attach it.
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 39
Radioactive Problem by Runge kutta IV order Method - Algorithm 1. define Function f (x,y) 2. input x0,y0 (x0 is time t0,y0 is the ini.no.of nuclei) 3. input step size,and the number of steps. 4. for i = 1 to n do k1= hf(x0,y0) k2= hf(x0+h/2, y0+1/2 k1) k3= hf(x0+h/2, y0+1/2 k2); k4= hf(x0+h, y0+k3) y1 = y0+ 1/6(k1+2*(k2+k3)+k4) x1= x0+h print x1,y1 y0 = y1; x0 = x1; next Draw Flow Chart Program // RK method #include <iostream.h> #include <math.h> #include <conio.h> #include <fstream.h> class RDecay { private: float N0,lamda,dt,endtime; public: RDecay(float n0, float halflife,float tstep,float et) { N0=n0; lamda= 0.693/halflife; dt=tstep; endtime= et; } float decay(float t,float N) { float dNbydt; dNbydt = -N*lamda; return dNbydt; } void RKmethod(); };
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 40
void RDecay::RKmethod() { float N[500],time[500]; float k1,k2,k3,k4,t,Nu; int nsteps,i=0; ofstream fout("c:\\tc\\bin\\RDRK4.dat"); nsteps= (int) (endtime/dt); cout.precision(4); cout.setf(ios::showpoint); time[0]= 0; N[0]= N0; cout<<"\n"<<setw(4)<<i<<setw(10)<<time[i]<<setw(10)<<N[i]; fout<<"\n"<<setw(4)<<i<<setw(10)<<time[i]<<setw(10)<<N[i]; for (i=1;i<=nsteps;i++) { t = time[i-1]; // current time Nu = N[i-1]; // current concentration k1= dt*decay(t,Nu); // first step k2= dt*decay(t+dt/2.0,Nu+k1/2.0); // second k3= dt*decay(t+dt/2.0,Nu+k2/2.0); // third k4= dt*decay(t+dt,Nu+k3); //fourth N[i]= Nu+ 1/6.0 * (k1+ 2*(k2+k3)+k4); // update time[i]=time[i-1]+dt; cout<<"\n"<<setw(4)<<i<<setw(10)<<time[i]<<setw(10)<<N[i]; fout<<"\n"<<setw(4)<<i<<setw(10)<<time[i]<<setw(10)<<N[i]; } fout.close(); getch(); }
void main() { float N0,halflife,dt,tmax; cout<<"\n Enter the following inputs"; cout<<"\n Initial Number of Nuclei :" ; cin >>N0; cout<<"\n Half Life Period :" ; cin>>halflife; cout<<"\n Time step (days): :"; cin>>dt; cout<<"\n End Time (days) :"; cin>>tmax; RDecay Rd(N0,halflife,dt,tmax); Rd.RKmethod(); cout<<"\n Result is in the file c:\\tc\\bin\\RDRK4.dat”; getch(); } Note: plot a graph in Excel using the generated data which is available in the file Rdrk4.dat and attach it.
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 41
II. Newton's Law of Cooling Newton's Law of cooling states that the rate of change of the temperature of an object is proportional to the difference between its own temperature and the ambient temperature (ie. temperatue of the surroundings) dT /dt = -k (T-S) T -> Temperature of the Object S -> Surrounding Temperature k -> Proportionality constant, depends on the surface property of the material The direct solution : The temperature of the object at time 't' is T(t) = S+ (T-S) exp(-kt) Newtons' Law of Cooling by RK4 method - Algorithm 1. define Function f (x,y) 2. input x0,y0 x0 ->time and y0-> temperature 3. input step size,and the number of steps. 4. for i = 1 to n do k1= hf(x0,y0) k2= hf(x0+h/2, y0+1/2 k1) k3= hf(x0+h/2, y0+1/2 k2); k4= hf(x0+h, y0+k3) y1 = y0+ 1/6(k1+2*(k2+k3)+k4) x1= x0+h print x1,y1 y0 = y1; x0 = x1; next Draw Flowchart based on the Algorithm
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 42
Progam // Newton Law of Cooling – RK method #include <iostream.h> #include <math.h> #include <conio.h> #include <fstream.h> class NCool { private: float temp0,surrtemp,constK,dt; float time0,endtime; public: NCool(float te,float st,float k,float tstep,float et) { temp0=te; surrtemp=st; constK=k; dt=tstep; endtime= et; } float tfall(float t,float temp) { float dTbydt; dTbydt = -constK *(temp-surrtemp); return dTbydt; } void RKmethod(); }; void NCool::RKmethod() { float temp[500],time[500]; float k1,k2,k3,k4,t,tem; ofstream fout("c:\\tc\\bin\\nlc.dat"); int nsteps,i=0; nsteps= (int) (endtime/dt); cout.precision(4); cout.setf(ios::showpoint); time[0]= 0; temp[0]= temp0; cout<<"\n"<<setw(4)<<i<<setw(10)<<time[i]<<setw(10)<< temp[i]; fout<<"\n" <<setw(4)<<i<<setw(10)<<time[i]<<setw(10)<< temp[i];
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 43
for (i=1;i<=nsteps;i++) { t = time[i-1]; // current time tem = temp[i-1]; // current temperature k1= dt*tfall(t,tem); // first step k2= dt*tfall(t+dt/2.0,tem+k1/2.0); // second k3= dt*tfall(t+dt/2.0,tem+k2/2.0); // third k4= dt*tfall(t+dt,tem+k3); //fourth temp[i]= tem+ 1/6.0 * (k1+ 2*(k2+k3)+k4); // update time[i]=time[i-1]+dt; cout<<"\n" << setw(4)<<i << setw(10)<<time[i] << setw(10)<< temp[i]; fout<<"\n" << setw(4)<<i << setw(10)<<time[i] << setw(10)<< temp[i]; } fout.close(); getch(); } void main() { float temp0,surtemp,kconst,dt,tmax; cout<<"\n Enter Initial Temperature :"; cin >>temp0; cout<<"\n Enter surrounding temperature :"; cin>>surtemp; cout<<"\n Enter constant k value /min :"; cin>>kconst; cout<<"\n Enter Time step : :"; cin>>dt; cout<<"\n Enter End Time (in minute) :"; cin>>tmax; NCool NLC(temp0,surtemp,kconst,dt,tmax); NLC.RKmethod(); cout<<"\n Result is in the file c:\\tc\\bin\\newton.dat”; getch(); } note: plot a graph between time and temperature using the data in 'newton.dat '
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 44
Curve Fitting : Fitting a Straight Line
In any branch of science, whenever a problem or experiment involves two or more variables (say
x,y) we have to find a suitable relation or law that may exist between the variables x and y from
the given set of observed values (xi,yi),i =1,2,…n. Such a relation that connects x and y is known
as empirical law.
Method of Least Squares Let (xi,yi), i=1,2,…n be the set of observed values of x and y. Let f(x) be a functional relationship
sought between x and y. Then di = yi – f(xi) is the the difference between the observed value of y
and the value of y determined by the functional relation is called the residual (or deviations).
Least squares principle is a widely used method for obtaining the estimates of the parameters in
a statistical model based on observed data. The best fit in the least-squares sense minimizes the
sum of squared residuals
The principle of least squares states that the sum of squares of the residual is minimum.
Thus the paramters involved in f(x) are choosen in such a way that ∑di2 is minimum.
Equations for fitting a line y = ax +b
∑y = a ∑x + nb ∑xy = a ∑x2 + b∑x
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 45
// Program : // Fitting a Straight Line Y= ax+b; A)Draw Flow chart B) Program #include <iostream.h> #include <math.h> #include <conio.h> #include <iomanip.h> class LinearFit { private: float xa[10],ya[10]; int n; float a,b; public: void GetInput(); void FindEquation(); void Interpolate(); }; void LinearFit::GetInput() { int i; /* cout<< "\n Enter number of points :"; cin>>n; cout<< "\n Enter X, and Y array elements:"; for(i=0;i<n;i++) { cout<<"\n Enter xa["<<i<<"]"; cin >> xa[i]; cout<<"\n Enter ya["<<i<<"]"; cin >> ya[i]; } */ // test data. Uncomment the above and comment the following lines xa[0]= 1; xa[1]= 2;xa[2]= 3 ;xa[3]= 4;xa[4]=5; ya[0]= 5; ya[1]= 7 ; ya[2]= 9;ya[3]=11;ya[4]=13; n=5; } void LinearFit::FindEquation() { float Sx,Sy,Sxy,Sx2; int i; Sx=Sy=Sxy=Sx2=0; for(i=0;i<n;i++) { Sx=Sx+xa[i]; Sy=Sy+ya[i]; Sxy = Sxy+ xa[i]*ya[i];
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 46
Sx2= Sx2+ xa[i]*xa[i]; } a= (n*Sxy - Sx*Sy)/ (n*Sx2 - Sx*Sx); b= Sy/n - a*Sx/n; // y =ax+b; cout.precision(4); cout.setf(ios::showpoint); cout<<"\n The required equation of linear fit is "; cout<<"\n Y = " <<setw(5)<<a<<"X + "<<setw(5)<<b; } // Interpolation using the fixed equation y=ax+b. void LinearFit::Interpolate() { float x,y; cout<<"\n Enter value of x:"; cin>>x; y = a*x+b; cout<<"\n Y("<<setw(4)<<x<<") =" << setw(5)<<y; } void main() { LinearFit Lf; Lf.GetInput(); Lf.FindEquation(); Lf.Interpolate(); getch(); }
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 47
// Interpolation using Newton Forward Difference Method #include <iostream.h> #include <math.h> #include <conio.h> #include <iomanip.h> class NIP // Numerical Differentiation using Newton Forward Differences { private: float xa[10],ya[10]; float x,p,h; float fd[10][10]; int n; float Fx; public: void GetInput(); void ComputeForwardDifference(); void Interpolate(); void PrintSolution(); }; void NIP::GetInput() { int i; /* cout<< "\n Enter number of points :"; cin>>n; cout<< "\n Enter X, and Y array elements:"; for(i=0;i<n;i++) { cout<<"\n Enter xa["<<i<<"]"; cin >> xa[i]; cout<<"\n Enter ya["<<i<<"]"; cin >> ya[i]; } cout <<"\n Enter value of X to interpolate "; cin>>x; h=xa[1]-xa[0]; p=(x-xa[0])/h; */ // Test Data. Find the value of y(0.3). n=6; xa[0]= 0.20; xa[1]=0.22;xa[2]=0.24;xa[3]=0.26;xa[4]=0.28;xa[5]=0.30; ya[0]=1.6596; ya[1]=1.6698; ya[2]= 1.6804; ya[3]=1.6912; ya[4]=1.7024;ya[5]=1.7139; x=0.23; h=xa[1]-xa[0]; p=(x-xa[0])/h; }
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 48
void NIP::ComputeForwardDifference() { int i,j; for(j=0;j<n-1;j++) { for(i=0;i<n-j-1;i++) { if(j==0) { fd[i][j] = ya[i+1]-ya[i]; } else fd[i][j] = fd[i+1][j-1]- fd[i][j-1]; } cout<<"\n"; } } void NIP::Interpolate() { int j; float sum=ya[0]; float nu=1; float de=1; cout <<"\n Pis = "<<p; for(j=0;j<n-1;j++) { nu = nu*(p-j); de = de*(j+1); sum = sum + fd[0][j]* nu/de; cout <<"\n nu " << nu; } Fx= sum; getch(); } void NIP::PrintSolution() { int i,j; // print the Forward Difference table cout.precision(4); cout.setf(ios::showpoint); cout<<"\n Forward difference Table:\n"; for(j=0;j<n;j++) { for(i=0;i<n-j-1;i++) { cout << setw(10)<<fd[j][i] ; } cout<<"\n"; }
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 49
cout<<"\n------------------------------------------"; cout<<"\n Y = "<<x <<"is " << Fx; } void main() { NIP Ca; Ca.GetInput(); Ca.ComputeForwardDifference(); Ca.Interpolate(); Ca.PrintSolution(); getch(); }
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 50
// Numerical Differentiation for tabulated points // using Newton Forward Differences #include <iostream.h> #include <math.h> #include <conio.h> #include <iomanip.h> class NFDI { private: float xa[10],ya[10]; float x,p,h; float fd[10][10]; float derivative; int n; public: void GetInput(); void FindP(); void ComputeForwardDifference(); void FindDerivative(); void PrintSolution(); }; void NFDI::GetInput() { int i; /* cout<< "\n Enter number of points :"; cin>>n; cout<< "\n Enter X, and Y array elements:"; for(i=0;i<n;i++) { cout<<"\n Enter xa["<<i<<"]"; cin >> xa[i]; cout<<"\n Enter ya["<<i<<"]"; cin >> ya[i]; } cout <<"\n Enter derivative point X"; cin>>x; h=xa[1]-xa[0]; */ // Test Data n=6; xa[0]= 1;xa[1]=2;xa[2]=3;xa[3]=4;xa[4]=5;xa[5]=6; ya[0]=2.7183 ; ya[1]=3.3210 ; ya[2]= 4.0552;ya[3]=4.9530; ya[4]=6.0496 ;ya[5]=7.3891; x=1; h=xa[1]-xa[0]; }
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 51
void NFDI::FindP() { int i=0; while(x > xa[i]) i++; p=i; } void NFDI::ComputeForwardDifference() { int i,j; for(j=0;j<n-1;j++) { for(i=0;i<n-j-1;i++) { if(j==0) { fd[i][j] = ya[i+1]-ya[i]; } else fd[i][j] = fd[i+1][j-1]- fd[i][j-1]; } cout<<"\n"; } } void NFDI::FindDerivative() { int j; float sum=0; float term=1; for(j=0;j<n-p-1;j++) { sum = sum+ fd[p][j]/(j+1) *term; term=-term; } derivative= sum; } void NFDI::PrintSolution() { int i,j; // print the differnce table cout.precision(4); cout.setf(ios::showpoint); cout<<"\n Forward difference Table:\n"; for(j=0;j<n;j++) {
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 52
for(i=0;i<n-j-1;i++) { cout << setw(10)<<fd[j][i] ; } cout<<"\n"; } cout<<"\n------------------------------------------"; cout<<"\n Derivative at X= "<<x <<"is " << derivative; } void main() { NFDI Nd; Nd.GetInput(); Nd.FindP(); Nd.ComputeForwardDifference(); Nd.FindDerivative(); Nd.PrintSolution(); getch(); }
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 53
Evaluation of Simple integral using Montecarlo Method. Note: Copy the attached Rand.Txt file to TurboC Folder. And change the path in fopen() accordingly.
Monte Carlo integration methods are sampling methods, based on probability theory.
They rely on trials and randomness to reveal information
Monte Carlo methods are capable of handling quite complicated and large problems
The most famous early use of MC mehtod was by Enrico Fermi in 1930 - he used a random method to calculate the properties of the newly-discovered neutron.
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 54
Basic Idea of MC integration
Given a single valued function f(x) as shown in the figure above, the goal is to determine the
integral
The above integral is the area under the curve represented by a solid line in the above figure.
Note that out of the three points in the above figure only one pointfalls below the curve.
1. Draw random numbers in the x − y plane (dots in the graph)
2. Integral of function f is approximately given by the total area times the fraction of
points that fall under the curve f(x)
3. The greater the number of points the more accurate is the evaluation of this area
/montecarlo
#include <iostream.h> #include <conio.h> #include <math.h> #include <stdlib.h> #include <iomanip.h> #include <stdio.h> #define PI 22.0/7.0 // sample prob. integral a=1 to b=2 1/(x+2) dx. // try differnt n values n = 10, 25, 100, 150 and tabulate the // integral value. float fun(float x) { return 1.0/(x+2); // for a=1,b=2 the actual ans is 0.28768 } void main() {
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 55
int i=0,n,k,hits=0; float rn[500]; float x,y,a,b,sy=0,avey=0,val,rnd; float maxy; FILE * fp; clrscr(); fp= fopen("c:\\tC\\rand.txt","r"); if(fp==NULL) { cout<<"\n File open error"; exit(0); } while (!feof(fp)) { fscanf(fp,"%g",&rn[i]); i++; } cout <<"\n Enter Lower Limit :" ; cin >>a; cout <<"\n Enter Upper Limit :" ; cin >>b; cout <<"\n Enter N value "; cin>>n; maxy = fun(a)>fun(b)?fun(a):fun(b); randomize(); i=0; while(i<=n) { i++;
k=random(500); rnd = rn[k]; x = (b-a)*rnd+a; y= fun(x); if(y<=maxy) { sy=sy+y; hits++; cout<< "\n"<<setw(5) <<x <<", " <<setw(10)<<y; } } avey = sy/hits; val = avey*(b-a); cout <<"\n N =" <<n; cout <<"\n Value of integral = "<< val; getch(); }
S.T.Hindu College, Department of Physics M.Sc Physics Practical – Programming Problems in µP and C++
Dr.K.Elampari, Associate Professor of Physics, S.T.Hindu College 56
Estimation of value of PI using Pseudo Random Number Generation –Montecarlo Method. //montecarlo #include <iostream.h> #include <conio.h> #include <math.h> #include <stdlib.h> #include <iomanip.h> #include <stdio.h> // Estimation of PI - Montecarlo method using Pseudo Random Numbers // use differnet n values and check the value of pi // if n is large pi is close to the actual value. // try n=10 , n=25, n=50, n=75 n= 100 and tabulate your result. void main() { int i=0,n,k,cnt=0; float x,y; float Rand2(); float pi; cout <<"\n Enter No.of random numbers "; cin>>n; randomize(); cnt=0; for(i=1;i<=n;i++) { x = Rand2(); y = Rand2(); cout <<"\n " <<setw(15)<<x << setw(15)<<y; if( x*x +y*y <=1) cnt++; } pi = 4* cnt*1.0/n; cout <<"\n Value of Pi, using" << setw(4) << n <<" Random Numbers : "<<pi; } // Pseudo Random Generator float Rand2() { return (rand() / (double) (RAND_MAX + 1)); }