Я пишу программу, которая вычисляет E. Все хорошо и сделано, за исключением того, что выводимое значение E начинается с «3». вместо "2" Я понятия не имею, что вызывает это, и я уверен, что это что-то глупое. Должно быть что-то простое, но, видимо, я слишком слеп, чтобы найти это.
import java.math.BigDecimal; //To use for calculating E
public class ComputeE {
/* * The number of trailing numbers after the decimal */
public static final int PRECISION = 18;
/* To Prevent Rounding Errors */
public static final int PRECISION_OFFSET = 4;
public static void main(String[] args) {
/* * Declare and initialize variables */
BigDecimal e = new BigDecimal(0.0); //E to be returned
int iterations = 0; //Counter for iterations required
/* * Process for computing factorial */
for(int i = 0; i < PRECISION + PRECISION_OFFSET; i++)
{
iterations++;
BigDecimal numerator = new BigDecimal(1.0); // Setting Numerator
BigDecimal factorial = new BigDecimal(calcDenominator(i)); // Calculating Denominator
factorial = numerator.divide(factorial, PRECISION + PRECISION_OFFSET, BigDecimal.ROUND_UP); // Compute The Factorial
e = e.add(factorial); // Add The Factorial to E
}
e = e.setScale(PRECISION, e.ROUND_HALF_EVEN); //Cut Off Extra Digits
/* * Console Output */
System.out.println("Computed value of e : " + e);
System.out.println("Expected value of e : " + Math.E);
System.out.println("Required Iterations : " + iterations);
}//End of main
public static double calcDenominator(int n)
{
/* * Declare and initialize variables */
double denominator = 1.0; //Start the BigInt with 1
/* * Calculate Denominator */
for(int i = 1; i < n; i++)
{
denominator = denominator * i; // Multiply BigInteger by the BigInteger obtained with the int value i
}
return denominator;
} //End Method
}