golden ratio calculation with precision

260 Views Asked by At

I've got the task to calculate the golden ratio (phi = (1+ sqrt(5))/2). But I need to calculate it with about 50 decimal digits / decimal places and then round the result up to 30 decimal digits and print it on the console. I am allowed to use BigDecimal and MathContext. Does anyone have an idea how to calculate it? I am lost right now. Thanks

2

There are 2 best solutions below

0
On

I found this on the web. It can be used to verify your calculations.

String goldenRatio = 
"1.61803398874989484820458683436563811772030917980576286213544862270526046281890" +
"244970720720418939113748475408807538689175212663386222353693179318006076672635";

You can verify the correctness of a regular calculation by

  • Verifying the length (don't forget the decimal point and the whole number digits).
  • verifying that it matches some initial part of the supplied answer.

To calculate normally, I used MathContext of precision = 30 and RoundingMode.HALF_UP.

This may not work for the way you are expected to do it. If you run into problems, folks here will be able to help.

I strongly suggest you post an attempt before asking for any additional help though.

0
On

I won't try to solve your problem for you! However I think to point you in a promising direction would be to look at the API: https://docs.oracle.com/javase/9/docs/api/java/math/BigDecimal.html and specifically at the constructor: BigDecimal(BigInteger unscaledVal, int scale, MathContext mc) I believe that if you experiment with these objects you can meet your goal. Note: sqrt was only added to BigDecimal in Java 9.

Good luck.