All pastes #113780 Raw Edit

Something

public java v1 · immutable
·published 2006-08-03 19:38 UTC
rendered paste body
import java.math.BigDecimal;/** * Computes the sum of the series 1 - 1/2 + 1/4 - 1/6 + 1/8 etc. Demonstrates * the use of {@link java.math.BigDecimal} in order to achieve high precision * floating point numbers.  *  * @author Tim De Pauw */public class BigDecTest {	/**	 * Size of the series.	 */	public final static int SIZE = 1000000;		/**	 * Number of digits to the right of the decimal point.	 */	public final static int SCALE = 50;		/**	 * Auxiliary constant. A {@link java.math.BigDecimal} representing the	 * number two.	 */	public final static BigDecimal TWO = new BigDecimal(2);	/**	 * Auxiliary constant. A {@link java.math.BigDecimal} representing the	 * number one.	 */	public final static BigDecimal ONE = new BigDecimal(1);	/**	 * Auxiliary constant. A {@link java.math.BigDecimal} representing the	 * number negative one.	 */	public final static BigDecimal NEG_ONE = new BigDecimal(-1);		public static void main (String[] args) {		System.out.println("Size:   " + SIZE);		System.out.println("Scale:  " + SCALE);		BigDecimal sum = ONE;		long start = System.currentTimeMillis();		for (int i = 1; i < SIZE; i++)			sum = sum.add((i % 2 == 0 ? ONE : NEG_ONE)				.divide(TWO.multiply(new BigDecimal(i)),					SCALE,					BigDecimal.ROUND_HALF_UP));		long end = System.currentTimeMillis();		System.out.println("Result: " + sum);		System.out.println("Time:   " + (end - start) / 1000.0 + " seconds");	}}