# Re: problem in my algorithm...

*From*: Lew <noone@xxxxxxxxxxxxx>*Date*: Sat, 24 Jan 2009 00:46:06 -0500

[G.P]Georgy™ wrote:

Hey Fred and Rossum!

I think I got what you are explaining to me:

/** Calculates factorial */

static int fact(int n) {

int result = 1;

while (n > 1) {

result *= n--;

}

return result;

}

/** Calculates e(x) */

static double e(int x) {

final double delta = 0.0001;

double result = 1.0;

double a = 1.0;

double b = 1.0;

double difference = 1.0;

int i = 1;

while (difference > delta) {

b = Math.pow(x, i)/fact(i);

result += b;

difference = b - a;

a = b;

i++;

}

return result;

}

I think it's solved.

Fred's version will be much faster and kinder to the stack.

Note that Fred omitted type declarations from his snippet:

You want something like this:

sum=1.;

n=1;

b=x;

a = 0;

while ( fabs(a-b) > tolerance ) {

a = b;

sum += a;

b = (a * x) / ++n;

}

I'd go with

<snippet>

private static final double TOLERANCE = 0.0001;

public final double ePower( double x )

{

return ePower( x, TOLERANCE );

}

public final double ePower( double x, double tolerance )

{

if ( tolerance <= Double.MIN_NORMAL )

{

tolerance = TOLERANCE;

}

double sum = 1.;

long n = 1L;

for ( double a = 0.0, b = x; Math.abs( a - b ) > tolerance; )

{

a = b;

sum += a;

b = (a * x) / ++n;

}

return sum;

}

</snippet>

I'm still confused in the following part of question: "with addiction

of two consecutive terms".

where is this addiction???

"Addition" - see Mark Space's answer.

--

Lew

.

**Follow-Ups**:**Re: problem in my algorithm...***From:*[G.P]Georgy™

**References**:**problem in my algorithm...***From:*[G.P]Georgy™

**Re: problem in my algorithm...***From:*rossum

**Re: problem in my algorithm...***From:*[G.P]Georgy™

- Prev by Date:
**Re: problem in my algorithm...** - Next by Date:
**use single email for yahoo, gtalk , orkut and msn** - Previous by thread:
**Re: problem in my algorithm...** - Next by thread:
**Re: problem in my algorithm...** - Index(es):