Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.math.BigDecimal;
- /**
- * @author DevDio, created on 09.09.2017.
- */
- class CustomMath {
- /**
- * Bigger border number = bigger PI precision
- * AND longer run time because of calculations
- */
- private static final long COUNTER_BORDER = 10_000_000;
- private static boolean DEBUG = true;
- /**
- * Calculates PI number up until loop
- * reaches COUNTER_BORDER
- *
- * @return PI number of primitive double type
- */
- public static double getPi() {
- double pi = 0;
- long start = System.currentTimeMillis();
- // calculate PI number loop
- for(int i = 0; i < COUNTER_BORDER; i++) {
- pi += 4*((Math.pow(-1, i)) / (2*i + 1));
- }
- long end = System.currentTimeMillis();
- if(DEBUG) {
- System.out.println("Run time: " + (end - start) + " ms");
- }
- return pi;
- }
- /**
- * Calculates PI number up until loop
- * reaches COUNTER_BORDER
- *
- * @return PI number of BigDecimal type
- */
- public static BigDecimal getPiAsBigDecimal() {
- BigDecimal pi = BigDecimal.ZERO;
- long start = System.currentTimeMillis();
- // calculate PI number loop
- for(int i = 0; i < COUNTER_BORDER; i++) {
- double pow = Math.pow(-1, i);
- int i1 = (2 * i) + 1;
- double i2 = 4 * (pow / i1);
- pi = pi.add(new BigDecimal(i2)); // is new object creation really necessary?
- }
- long end = System.currentTimeMillis();
- if(DEBUG) {
- System.out.println("Run time: " + (end - start) + " ms");
- }
- return pi;
- }
- }
- public class Client {
- public static void main(String[] args) {
- System.out.println("Internal: ");
- System.out.println("PI: " + Math.PI);
- System.out.println("With primitives: ");
- System.out.println("PI: " + CustomMath.getPi());
- System.out.println("With objects: ");
- System.out.println("PI: " + CustomMath.getPiAsBigDecimal());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement