# Trying to estimate e^x with loops

I've been staring at this for a few hours, and I can't seem to figure out why my outputs are coming out too small. My outputs do what you'd expect, level off, they just level off to the wrong value. I'm very certain the error lies within the while loop of my main method, or the nested for loop, but I'll go ahead and post everything incase it is hiding somewhere else.

The purpose of this program is to estimate the value of e^x by summing 1 + x + x^2/2! + x^3/3! + ... + x^n/n!. It needs to output the sum for n take to each value between 1 and 10, along with the values of 50 and 100. So 12 outputs all together.

import java.io.*; import java.text.DecimalFormat; public class Ch3Ex7 { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static double x = 0; static DecimalFormat df = new DecimalFormat("0.00"); public static void main (String[] args) { mainMenu(); int counter = 1; double heldx = x; double holderx = 0; double denom = 1; double printx = 0; double f = 1; while (counter != 100) { x = x*heldx; denom++; for(int i = 2; i<=denom; i++) { f = f*i; } holderx = holderx + x/f; if ((counter > 0 && counter <= 10) || (counter == 50)) { printx = 1 + heldx + holderx; System.out.println(df.format(printx)); } counter++; } System.out.println(df.format(printx)); f = 0; x = 0; counter = 1; denom = 1; callMain(); } public static void mainMenu() { try { System.out.println("Requesting user input, press 0 to leave"); x = Integer.parseInt(br.readLine()); space(); if (x == 0) { System.exit(0); } } catch(IOException ioe) {} } public static void callMain() { String[] x = {"A" , "B"}; Ch3Ex7.main(x); } public static void space() { System.out.println(); } }

## Answers

The problem is with your "f" variable. You're trying to calculating the value every time, but you end up starting with your old value.

Get rid of that for loop and add f *= denom; in its place.