Question

Please fix this code so it compiles import java.math.BigDecimal; import java.lang.Math; public class Sequence { public...

Please fix this code so it compiles

import java.math.BigDecimal;

import java.lang.Math;

public class Sequence {

public static BigDecimal fact( int n ) {

BigDecimal result = BigDecimal.ONE;

while (n > 0) {

result = result.multiply(new BigDecimal(n + ""));

n--;

}

return result;

}

public static BigDecimal pow( BigDecimal a, int b ) {

BigDecimal result = a;

if(b == 0) {

return BigDecimal.ONE;

}

while ( b > 1 ) {

result = result.multiply(new BigDecimal(a + ""));

b--;

System.out.print("\n" + result + "\n");

}

return result;

}

public static BigDecimal Ramanujan( int n ) {

BigDecimal coefficient = BigDecimal.valueOf(Math.sqrt(8.0)).divide(BigDecimal.valueOf(9801)); //will multiply the sum by sqrt(8)/9801

BigDecimal pi_R = BigDecimal.ONE;

BigDecimal sum = BigDecimal.ZERO;

BigDecimal quotient;

BigDecimal numer;

BigDecimal denom;

for(int i = 0; i <= n; i++ ) {

BigDecimal bigN = BigDecimal.valueOf(n); //Now, when we need to do arithmetic with ints we can do that, and

//when we need arithmetic with BigDecimals we can do that.

numer = (BigDecimal.valueOf(26390).multiply(bigN));

numer = numer.add(BigDecimal.valueOf(1103));

numer = numer.multiply(fact( 4 * n ));

denom = pow( fact(n), 4 );

denom.multiply(pow(BigDecimal.valueOf(396), (4 * n)) );

quotient = numer.divide(denom);

sum.add(quotient);

}

pi_R = BigDecimal.ONE.divide(coefficient.multiply(sum));

return pi_R;

}

public static BigDecimal Chudnovsky( int n ) {

BigDecimal coefficient = BigDecimal.ONE.divide(BigDecimal.valueOf(53360.0).multiply(BigDecimal.valueOf(Math.sqrt(640320.0)))); //will multiply the sum by 1/53360sqrt(640320)

BigDecimal pi_C = BigDecimal.ONE;

BigDecimal sum = BigDecimal.ZERO;

BigDecimal quotient;

BigDecimal numer;

BigDecimal denom;

for(int i = 0; i <= n; i++ ) {

BigDecimal bigN = BigDecimal.valueOf(n);

numer = BigDecimal.valueOf(545140134).multiply(bigN);

numer = numer.add(BigDecimal.valueOf(13591409.0));

numer = numer.multiply(pow( BigDecimal.valueOf(-1), n ));

numer = numer.multiply(fact( 6 * n ));

denom = pow( fact(n), 3 );

denom = denom.multiply( fact( 3 * n ));

denom = denom.multiply( pow( BigDecimal.valueOf(340320), (3*n) ));

quotient = numer.divide(denom);

sum.add(quotient);

}

pi_C = BigDecimal.ONE.divide(coefficient.multiply(sum));

return pi_C;

}

public static void main(String[] args) {

BigDecimal ramanPi = Ramanujan(10000);

BigDecimal chudPi = Chudnovsky(10000);

System.out.print("Ramanujan's algorithm for pi, for n = 10,000:\n" + ramanPi + "\n");

System.out.print("Chudnovsky brothers' algorithm for pi, for n = 10,000:\n" + chudPi);

}

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Hi,

Considering that algorithm is correct for pi calculation , if i have understood your question correctly you are facing compilation errors.

After i tried and executing above program,

I faced below compilation error,

Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
   at java.math.BigDecimal.divide(BigDecimal.java:1690)
   at Sequence.Ramanujan(Sequence.java:50)
   at Sequence.main(Sequence.java:137)

this error for below lines,

1>

public static BigDecimal Ramanujan( int n ) {

BigDecimal coefficient = BigDecimal.valueOf(Math.sqrt(8.0)).divide(BigDecimal.valueOf(9801)); //will multiply the sum by sqrt(8)/9801

-----

}

solution:

When a MathContext object is supplied with a precision setting of 0 (for example, MathContext.UNLIMITED), arithmetic operations are exact, as are the arithmetic methods which take no MathContext object. (This is the only behavior that was supported in releases prior to 5.)

As a corollary of computing the exact result, the rounding mode setting of a MathContext object with a precision setting of 0 is not used and thus irrelevant. In the case of divide, the exact quotient could have an infinitely long decimal expansion; for example, 1 divided by 3.

If the quotient has a nonterminating decimal expansion and the operation is specified to return an exact result, an ArithmeticException is thrown. Otherwise, the exact result of the division is returned, as done for other operations.

you can find this explaination in java 8 docs also.

BigDecimal coefficient = BigDecimal.valueOf(Math.sqrt(8.0)).divide(BigDecimal.valueOf(9801),2,RoundingMode.HALF_UP);

where 2 is precision and RoundingMode.HALF_UP is rounding mode

RoundingMode are Enum constants, you could choose any of this UP, DOWN, CEILING, FLOOR, HALF_DOWN, HALF_EVEN, HALF_UP

In this Case HALF_UP, will have this result:

2.4 = 2   
2.5 = 3   
2.7 = 3

2>same things need to be corrected for

public static BigDecimal Chudnovsky( int n )
{

BigDecimal coefficient = BigDecimal.ONE.divide(BigDecimal.valueOf(53360.0).multiply(BigDecimal.valueOf(Math.sqrt(640320.0))),2,RoundingMode.HALF_EVEN);

-----

}

Thanks,

kindly upvote.

Add a comment
Know the answer?
Add Answer to:
Please fix this code so it compiles import java.math.BigDecimal; import java.lang.Math; public class Sequence { public...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I need a java flowchart for the following code: import java.util.*; public class Main {   ...

    I need a java flowchart for the following code: import java.util.*; public class Main {    public static void main(String[] args) {    Scanner sc=new Scanner(System.in);           System.out.print("Enter the input size: ");        int n=sc.nextInt();        int arr[]=new int[n];        System.out.print("Enter the sequence: ");        for(int i=0;i<n;i++)        arr[i]=sc.nextInt();        if(isConsecutiveFour(arr))        {        System.out.print("yes the array contain consecutive number:");        for(int i=0;i<n;i++)        System.out.print(arr[i]+" ");       ...

  • Rational will be our parent class that I included to this post, Implement a sub-class MixedRational....

    Rational will be our parent class that I included to this post, Implement a sub-class MixedRational. This class should Implement not limited to: 1) a Constructor with a mathematically proper whole, numerator and denominator values as parameters. 2) You will override the: toString, add, subtract, multiply, and divide methods. You may need to implement some additional methods, enabling utilization of methods from rational. I have included a MixedRational class with the method headers that I used to meet these expectations....

  • I just need to add comment for the code blow. Pleas add comment for each method...

    I just need to add comment for the code blow. Pleas add comment for each method and class if comments left out. package exercise01; /*************************************************************************** * <p> This program demonstrates the technique of recursion and includes * recursive methods that are defined for a variety of mathematical * functions. *    * <br>A recursive method is one that directly or indirectly calls itself * and must include: * <br>(1) end case: stopping condition * which terminates/ends recursion * <br>(2) reduction:...

  • Need help with the UML for this code? Thank you. import java.util.Scanner;    public class Assignment1Duong1895...

    Need help with the UML for this code? Thank you. import java.util.Scanner;    public class Assignment1Duong1895    {        public static void header()        {            System.out.println("\tWelcome to St. Joseph's College");        }        public static void main(String[] args) {            Scanner input = new Scanner(System.in);            int d;            header();            System.out.println("Enter number of items to process");            d = input.nextInt();      ...

  • please evaluate the following code. this is JAVA a. class Car { public int i =...

    please evaluate the following code. this is JAVA a. class Car { public int i = 3; public Car(int i) { this.i = i; } } ... Car x = new Car(7), y = new Car(5); x = y; y.i = 9; System.out.println(x.i); b. class Driver { public static void main(String[] args) { int[] x = {5, 2, 3, 6, 5}; int n = x.length; for (int j = n-2; j > 0; j--) x[j] = x[j-1]; for (int j...

  • What is the output of the following program? import java.util.ArrayList; import java.util.Collections; import java.util.List; public class...

    What is the output of the following program? import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Test implements Comparable<Test> private String[] cast; public Test( String[] st) cast = st; public int compareTo( Test t) if ( cast.length >t.cast.length ) t return +1; else if cast.length < t.cast.length return -1; else return 0; public static void main( String[] args String[] a"Peter", "Paul", "Mary" String[] b_ { "Мое", ''Larry", "Curly", String [ ] c = { ·Mickey", "Donald" }; "Shemp" }; List<Test>...

  • Can you help me with this code in Java??? import java.util.Scanner; public class Main { public...

    Can you help me with this code in Java??? import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); int rows = 3; int columns = 4; int[][] arr = new int[rows][columns]; for(int i = 0; i < rows; ++i) { for(int j = 0; j < columns; ++j) { System.out.println("Enter a value: "); arr[i][j] = scan.nextInt(); } } System.out.println("The entered matrix:"); for(int i = 0; i < rows; ++i) { for(int j...

  • need help to write the main method as the template import java.util.*; public class oBST {...

    need help to write the main method as the template import java.util.*; public class oBST { static float optimalBST(String words[], float freq[], int n) { //2D dp matrix float dp[][] = new float[n + 1][n + 1]; int root[][] = new int[n+1][n+1]; // For a single word, cost is equal to frequency of the word for (int i = 0; i < n; i++) dp[i][i] = freq[i]; // Now consider for size 2, 3, ... . for (int L =...

  • Please fix my code so I can get this output: Enter the first 12-digit of an...

    Please fix my code so I can get this output: Enter the first 12-digit of an ISBN number as a string: 978013213080 The ISBN number is 9780132130806 This was my output: import java.util.Scanner; public class Isbn { private static int getChecksum(String s) { // Calculate checksum int sum = 0; for (int i = 0; i < s.length(); i++) if (i % 2 == 0) sum += (s.charAt(i) - '0') * 3; else sum += s.charAt(i) - '0'; return 10...

  • Solver.java package hw7; import java.util.Iterator; import edu.princeton.cs.algs4.Graph; import edu.princeton.cs.algs4.BreadthFirstPaths; public class Solver {    public static...

    Solver.java package hw7; import java.util.Iterator; import edu.princeton.cs.algs4.Graph; import edu.princeton.cs.algs4.BreadthFirstPaths; public class Solver {    public static String solve(char[][] grid) {        // TODO        /*        * 1. Construct a graph using grid        * 2. Use BFS to find shortest path from start to finish        * 3. Return the sequence of moves to get from start to finish        */               // Hardcoded solution to toyTest        return...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT