Use Java BigDecimal to complete the calculation of the percentage π

zhaozj2021-02-16  59

Package chu_nz_baby;

Import java.util. *; import java.math. *;

/ ** *

Title: Calculation of π circumference *

Description: Complete the calculation of the CHUDNOVSKY formula using Java BigDecimal. You can specify the calculation accuracy and calculation parameters. *

Copyright: Copyright (c) 2004 * Calculation method of the peripheral rate #Chudnovsky formula * The calculation process of the circumference π * @AuThor chu_nz_baby@hotmail.com * @version 1.0 * /

PUBLIC CLASS PI {

PRIVATE BIGDECIMAL RESULT

Public pi () {

}

Public void Run (INT N, INT Scale) {if (System.getProperty ("Debug")! = null) {system.out.println ("n =" n);}

BigDecimal Upper = New BigDecimal (426880.0000 * math.sqrt (10005.0000)); Upper = Upper.setscale (Scale, BigDecimal.Round_HALF_EVEN);

IF (System.getProperty ("debug")! = null) {system.out.println ("Upper =" Upper);}

BigDecimal Downer = BigDecimal.Valueof (0);

For (int i = 0; i <= n; i ) {BIGDECIMAL D0 = Factorial (6 * i) .Multiply (NEW BIGDECIMAL (545140134 * i 13591409)); BigDecimal D1 = Factorial (i); BigDecimal D2 = Pow (D1, 3); BigDecimal D3 = Factorial (3 * i); BigDecimal D4 = POW (-640320, 3 * i); BigDecimal D5 = D2.Multiply (D3); BigDecimal D6 = D4.Multiply (D5); BigDecimal D = d0.divide (D6, BigDecimal.Round_Half_Even);

Downer = DOWNER.ADD (D);

}

IF (System.getProperty ("Debug")! = null) {system.out.println ("DOWNER =" Downer;}

IF (System.getProperty ("debug")! = null) {system.out.println ("Upper.scale =" Upper.scale ()); System.Sout.println ("Downer.scale =" Downer. Scale ());} result = Upper.divide (Downer, BigDecimal.Round_Half_Even);

IF (System.getProperty ("Debug")! = null) {system.out.println ("result.scale =" result.scale ());}

}

Public BigDecimal getResult () {

Return Result;}

Public Static BigDecimal Pow (Double Val, Int Power) {Return Pow (New BigDecimal (VAL), POWER)

Public Static BigDecimal Pow (BigDecimal Val, INT POWER) {BigDecimal Value = BigDecimal.Valueof (1); for (INT I = 1; I <= Power; i ) {value = value.multiply (val);} return Value;

Public Static BigDecimal Factorial (INT N) {BigDecimal Value = BigDecimal.Valueof (1); for (INT i = 1; i <= n; i ) {value = value.multiply (BigDecimal.Valueof (i));} return Value;

Public static void main (string [] args) {if (args.length <2) {system.out.println ("USAGE:" "java nz-baby.pi" "parameter (0- infinity) accuracy (1 -4294967296) ")"); system.out.println ("USAGE:" "java nz-baby.pi" "n (0-) scale (1-4294967296)") ")"); system.exit (-1);}

INT n = integer.parseint (args [0]); int scale = integer.parseint (args [1]);

System.out.println ("Palgorithm n =" n "scale =" scale); system.out.println ("start:" new date (system.currenttimemillis)); pi p = new pi ); P.Run (n, scale); system.out.println ("end:" new date (system.currenttimemillis); system.out.println ("result =" p.getResult ()) }}

转载请注明原文地址:https://www.9cbs.com/read-21852.html

New Post(0)