variable assignment - Computing Pi in Java -
this weeks assignment in programming compute pi in java using basis assignment:
(for 80% of marks): using while or do-while loop write programme compute pi using next equation: pi = 3 + 4/(2*3*4) - 4/(4*5*6) + 4/(6*7*8) - 4/(8*9*10) + ... allow user specify number of terms (5 terms shown) utilize in computation. each time around loop 1 term should added estimate pi. (for 20% of marks): alter solution part 1 user allowed specify precision required between 1 , 8 digits (i.e. number of digits correct; e.g. 5 digits pi 3.14159), rather number of terms. status on loop should altered continues until required precision obtained. note need submit sec version of programme (assuming have working).i'm able utilize above method compute pi, thats lecturer wants. ive got far, although code keeps giving me same wrong reply every number , different wrong reply each odd number. im still on part 1 havent got right reply yet able progress onto part 2.
all help great, programme needs submitted tueday. in advance!
import java.util.scanner; public class computepi { public static void main(string[] args) { system.out.print( "please come in amount of decimal " + "digits of pi, set too"); scanner termscan = new scanner( system.in ); int term = termscan.nextint(); termscan.close(); double pi = 3.0; int loopcount = 2; int number = 2; while ( loopcount <= term ) { if (loopcount % 2 == 0) { pi = pi + ( 4.0/ ((number) * (number+1) * (number+2)) ); } else { pi = pi - ( 4.0 / ((number) * (number+1) * (number+2)) ); } number = number + 2; loopcount++; } system.out.print( "the value of pi in " + term + " terms equal " + pi); } }
i not going give code (you can figure out yourself, i'm certain), i'll give location problem.
in negative terms, adding 2
each number multiplied together. however, adding 2
each number in every iteration of loop: numberxxx + 2
part should numberxxx
.
you incrementing numberxxx
variables when loopcount
1
. in fact, if (loopcount == 1)
part unnecessary, since initialize pi
. should remove if
block there , switch loopcount % 2 == x
blocks around.
i'll give general advice things might want consider in code.
you don't need constants4.0
in variable. replace fourconstant
4.0
. you don't need utilize else if
3rd block: if loopcount % 2
not 0
1
. loopcount
can integer values, should int
. double
consumes memory (this not problematic here, may in big programs) , can in cases lead errors (too big numbers may cause rounding errors). you don't need 3 variables numberone
, numbertwo
, numberthree
; can represented numberone
, numberone + 1
, numberone + 2
. java variable-assignment scientific-computing pi
No comments:
Post a Comment