Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package picalculator;
- import java.math.BigDecimal;
- import java.math.MathContext;
- import java.util.ArrayList;
- public class Vars {
- public static final BigDecimal ZERO = new BigDecimal("0" );
- public static final BigDecimal ONE = new BigDecimal("1");
- public static final BigDecimal TWO = new BigDecimal("2");
- public static final BigDecimal FOUR = new BigDecimal("4");
- public static BigDecimal LastPI = ZERO.plus();
- public static BigDecimal PI = new BigDecimal( "0.0", MathContext.DECIMAL128 );
- public static BigDecimal Count = new BigDecimal("0");
- public static ArrayList<BigDecimal> PIAvgs = new ArrayList<>( 1000000 );
- public static boolean shouldStop = false;
- public static final Object piLock = new Object();
- }
- package picalculator;
- import java.math.BigDecimal;
- import java.math.MathContext;
- import static picalculator.Vars.*;
- public class BDFuncs {
- // The magic happens here
- // This function calculates the next PI in the series, as well as the actual child series while creating other news (see updateAverage()).
- public static void nextCicle() {
- synchronized ( piLock ) {
- LastPI = PI.plus();
- if ( shouldSubstract() ) PI = PI.subtract( getCicleTerm() );
- else PI = PI.add( getCicleTerm() );
- updateAverage();
- Count = Count.add( ONE );
- }
- }
- private static BigDecimal getCicleTerm() {
- return ONE.divide( Count.multiply( TWO ).add( ONE ), MathContext.DECIMAL128 );
- }
- private static boolean shouldSubstract() {
- if ( Count.remainder( TWO ).compareTo( ONE ) == 0 ) return true;
- else return false;
- }
- // This function works by calculating ONLY the averages at the last side of the tree.
- // It first calcles the last average of the first child series, and then using that
- // average and the last average of the same child series(if any), calculates its average
- // and sets it as the second child series' last child, repeating so until it reaches the
- // top of the tree, or in this case, while the index is more or equal than 0.
- private static void updateAverage() {
- PIAvgs.add( average( LastPI, PI ) );
- for ( int i = PIAvgs.size() - 2; i >= 0; i-- ) {
- PIAvgs.set( i, average( PIAvgs.get( i ) , PIAvgs.get( i + 1 ) ) );
- }
- }
- private static BigDecimal average( BigDecimal bd1, BigDecimal bd2 ) {
- return bd1.add( bd2 ).divide( TWO );
- }
- public static BigDecimal[] getData() {
- BigDecimal[] tempArr = new BigDecimal[3];
- synchronized ( piLock ) {
- tempArr[0] = PI.plus();
- tempArr[1] = ( PIAvgs.isEmpty() ? ZERO : PIAvgs.get(0) );
- tempArr[2] = Count.plus();
- }
- return tempArr;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement