Mathematical constant e generator in Java

Java — Dillon @ 11:59 pm

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

1 Comment »

  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;
    }

    Comment by James — May 1, 2003 @ 3:57 pm

RSS feed for comments on this post.

Leave a comment

This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 Unported License.
(c) 2012 SQUARISM | powered by WordPress with Barecity