Advertisement
Guest User

Untitled

a guest
Sep 9th, 2017
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.08 KB | None | 0 0
  1. import java.math.BigDecimal;
  2.  
  3. /**
  4.  * @author DevDio, created on 09.09.2017.
  5.  */
  6. class CustomMath {
  7.  
  8.     /**
  9.      * Bigger border number = bigger PI precision
  10.      * AND longer run time because of calculations
  11.      */
  12.     private static final long COUNTER_BORDER = 10_000_000;
  13.  
  14.     private static boolean DEBUG = true;
  15.  
  16.     /**
  17.      * Calculates PI number up until loop
  18.      * reaches COUNTER_BORDER
  19.      *
  20.      * @return PI number of primitive double type
  21.      */
  22.     public static double getPi() {
  23.  
  24.         double pi = 0;
  25.  
  26.         long start = System.currentTimeMillis();
  27.  
  28.         // calculate PI number loop
  29.         for(int i = 0; i < COUNTER_BORDER; i++) {
  30.             pi += 4*((Math.pow(-1, i)) / (2*i + 1));
  31.         }
  32.  
  33.         long end = System.currentTimeMillis();
  34.  
  35.         if(DEBUG) {
  36.             System.out.println("Run time: " + (end - start) + " ms");
  37.         }
  38.  
  39.         return pi;
  40.     }
  41.  
  42.     /**
  43.      * Calculates PI number up until loop
  44.      * reaches COUNTER_BORDER
  45.      *
  46.      * @return PI number of BigDecimal type
  47.      */
  48.     public static BigDecimal getPiAsBigDecimal() {
  49.  
  50.         BigDecimal pi = BigDecimal.ZERO;
  51.  
  52.         long start = System.currentTimeMillis();
  53.  
  54.         // calculate PI number loop
  55.         for(int i = 0; i < COUNTER_BORDER; i++) {
  56.             double pow = Math.pow(-1, i);
  57.             int i1 = (2 * i) + 1;
  58.             double i2 = 4 * (pow / i1);
  59.             pi = pi.add(new BigDecimal(i2)); // is new object creation really necessary?
  60.         }
  61.  
  62.         long end = System.currentTimeMillis();
  63.  
  64.         if(DEBUG) {
  65.             System.out.println("Run time: " + (end - start) + " ms");
  66.         }
  67.  
  68.         return pi;
  69.     }
  70. }
  71.  
  72. public class Client {
  73.  
  74.     public static void main(String[] args) {
  75.  
  76.         System.out.println("Internal: ");
  77.         System.out.println("PI: " + Math.PI);
  78.         System.out.println("With primitives: ");
  79.         System.out.println("PI: " + CustomMath.getPi());
  80.         System.out.println("With objects: ");
  81.         System.out.println("PI: " + CustomMath.getPiAsBigDecimal());
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement