SQUARISM addicted to pixels

Mathematical constant e generator in Java

Posted on April 30, 2003

A small class to generate the mathematical constant "e". Complete with timer and digits per second clock. Unpolished. Here's a quick benchmark and you can see that it doesn't scale.

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;

/**
* calculate mathmatical constant e
*/

public class ECalculator {
private static final int numberOfDigits = 1000;
public static void main(String[] args) {
ECalculator myEClass = new ECalculator();
System.out.println("Calculating e to " + numberOfDigits + " digits ...\n");
Date start = new Date();
BigDecimal e = myEClass.doCalculation();
Date stop = new Date();
long elapsedSeconds = (stop.getTime()-start.getTime()) / 1000;
System.out.println("e is: \n" + e);
if (elapsedSeconds

Filed under: Java Leave a comment
Comments (1) Trackbacks (0)
  1. Try this optimization

    (Forgive the formatting)
    // — Add a constant variable
    public static final BigInteger BIG_INT_CONSTANT = BigInteger.valueOf(i);

    /* the useful stuff */
    private BigDecimal doCalculation()
    {
    BigInteger factorialTotal = new BigInteger(“1″);
    BigDecimal bigE = new BigDecimal(“1″);

    for (int i = 0; i < numberOfDigits; i++)
    {
    /*
    * The Following adheres to the formula:
    *
    * e = 1/0! + 1/1! + 1/2! + 1/3! + 1/4! + …
    *
    */

    // increment factorial by multiplying itself by itself
    factorialTotal = factorialTotal.add(
    factorialTotal.multiply(BIG_INT_CONSTANT));
    // — ^^^^^^^^^^^^^ Use the constant variable
    // e grows and becomes more accurate
    bigE = bigE.add(
    BIG_INT_CONSTANT.divide(new BigDecimal(factorialTotal), numberOfDigits, BigDecimal.ROUND_HALF_UP));
    // — ^^^^^^^^^ Use the BigInteger parameter constructor

    }

    return bigE;
    }


Leave a comment


Trackbacks are disabled.