₦airaland Forum

Welcome, Guest: RegisterLoginWith GoogleTrendingRecentNew

Stats: 3,325,024 members, 8,419,980 topics. Date: Thursday, 04 June 2026 at 08:43 AM

Toggle theme

Simple Java Problem - Programming - Nairaland

Nairaland ForumScience/TechnologyProgrammingSimple Java Problem (1915 Views)

1 Reply (Go Down)

Simple Java Problem by eazyd(op): 11:30am On Nov 20, 2012
Estimate and print the mathematical constant e (equal to 2.71828). You can estimate its value using the formula:
e = 1 + 1/1! + 1/2! + 1/3! +1/4! + ....+ 1/k! + ...
Quit looping when the term 1/k! becomes less than 1E-04.
Re: Simple Java Problem by eazyd(op): 11:33am On Nov 20, 2012
Specially for @Javanian - love the way you code! smiley
Re: Simple Java Problem by eazyd(op): 11:42am On Nov 20, 2012
solution-

public class ConstantValue
{
public static void main (String [] args)
{
// declare data;
double e;
double k;
double denom;
double term;

// initialize the data;
e = 1;
k = 0;
denom = 1;

do {

k++;
denom*= k;

term = 1/denom;

e += term;
System.out.println("The value of constant e = "+e);
}

while (term >= 1E-04);


}
}
Re: Simple Java Problem by Nobody:
.
Re: Simple Java Problem by Javanian:

public class ConstantValue {
public static void main(String[] args) {
double term = 2, e = 0;
final double difference = 0.0000000001; //or 1E-04

for (int n = 0; term > difference; n++) {
term = 1.0 / find_denominator(n);
e += term;
System.out.println("The Value of Constant e" + e);
}
}

public static double find_denominator(int n) {

if (n == 0 || n == 1)
return 1.0;

return n * find_denominator(n - 1);
}
}
Re: Simple Java Problem by Javanian: 1:23pm On Nov 20, 2012
eazyd: Specially for @Javanian - love the way you code! smiley
Am Flattered grin
Re: Simple Java Problem by eazyd(op): 1:46pm On Nov 20, 2012
Javanian: Am Flattered grin
As usual, you delivered promptly!
Re: Simple Java Problem by xcitedjay(m): 8:45pm On Nov 24, 2012
Just thought I should add a solution using a while loop

public class ConstantValue{
public static void main(String[] args){
int k = 1;
double term = k, e = 0;
while(term > 1E-04){
e += term;
term = 1/compute(k++);
}
System.out.println("Constant e = " + e);
}
static double compute(int k){
if(k==1)
return k;
return k * compute(k-1);
}
}
Re: Simple Java Problem by Javanian: 3:25am On Jul 25, 2014
bump
1 Reply

Help A Java Newbie With This Simple Java ProgramPlease Solve This Java Problem.Pls, Help Me In This Java Problem234

3 Reasons Why You Should Not Miss Becoming an App Developer today (pics)What Next After Learning Core JAVA, HTML And CSSWhat Is Ui And Ux