Reputation: 11
Need help calculating pie with leibniz series using Mips Assembly Lang.
I would input 10000 and it goes further from pie. I think my formula is wrong maybe? I am not to sure. I used a conditional branch to determine if the term is greater than zero or less than.
.text
.globl main
main:
la $a0,prompt # print string
li $v0,4 # service 4
syscall
li $v0,5 # read int into $v0
syscall # service 5
#Evaluate Pie
move $t2,$v0 #Move user number into $s0
li $t1,1 #Loop counter
li.s $f2,0.0 #Sum
li.s $f4,0.0 #Add to sum
li.s $f6,0.0 #Comparison 0.0
li.s $f8,1.0 #Use as floating i
li.s $f10,1.0 #Temp 1.0
li.s $f14,2.0 #Constant 2.0
loop:
beq $t1,$t2,done #While 1<User Input Cont
mul.s $f4,$f14,$f8 #2.0*I
add.s $f4,$f4,$f10 #2.0*I+1.0
div.s $f4,$f10,$f4 #1.0/2.0*I+1.0
addi $t1,$t1,1 #Increment Loop Counter
add.s $f8,$f8,$f10 #Increment Float I
c.lt.s $f6,$f4 #Is 0.0 < Add to sum
bc1t yes
sub.s $f2,$f4,$f2 #No so subtract
yes: add.s $f2,$f4,$f2 #Yes so add
j loop
done:
mov.s $f12,$f2 #Move sum to float print
li $v0,2 # print sum
syscall
li $v0,10 # exit
syscall
##
## Data Segment
##
.data
prompt: .asciiz "Enter number of terms: "
Upvotes: 0
Views: 554
Reputation: 7674
There's two problems with the comparison before yes
:
1) $f4
will never be negative, so the comparison will always go to yes
and you'll always be adding terms to the sum.
2) If $f4
was ever negative and the check went to the next line instead, you're missing a j loop
after the subtraction; it would subtract and then flow right into the yes
label, which would just cancel out the subtraction.
The operand order on the sub
is backwards (sub $a,$b,$c
will do $a = $b - $c
). You also need to start the floating i
at 0 instead of 1.
With all those fixes, I get:
...
li.s $f8,0.0 #Use as floating i
...
loop:
beq $t1,$t2,done #While 1<User Input Cont
mul.s $f4,$f14,$f8 #2.0*I
add.s $f4,$f4,$f10 #2.0*I+1.0
div.s $f4,$f10,$f4 #1.0/2.0*I+1.0
addi $t1,$t1,1 #Increment Loop Counter
add.s $f8,$f8,$f10 #Increment Float I
andi $t3,$t1,1
beq $t3,$zero,even
sub.s $f2,$f2,$f4
j loop
even:
add.s $f2,$f4,$f2
j loop
...
This outputs 0.78542465, which is roughly pi/4.
Upvotes: 1