Re: problem in my algorithm...

[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".

--
Lew
.

Relevant Pages

• Re: Performance of hand-optimised assembly
... Why not use unsigned for sum in the test harness? ... int is better yet because the output will then be same across machines. ... gcc -O3 seems ... but taking an average by eye my best asm version was *slower* than ...
(comp.lang.c)
• Re: [PATCH] input: Introduce light-weight contact tracking
... seems the patch was damaged somehow. ... static int illegal(int nslot, int npos, unsigned x) ... int i, j, sum; ...
(Linux-Kernel)
• Re: Algorithm
... Wont sum of all positive numbers will be the largest sub-array? ... int getint ... struct sofar *next; ... struct sofar *discard(struct sofar *trail) ...
(comp.lang.c)
• Re: Arrays vs Buffers
... and the next array access is dependent on the value ... and then return the overall sum to the test harness ... nextPointer(int[] array, int point) ... pointer = nextPointer; ...
(comp.lang.java.programmer)
• Re: Help Resource Counters Scale Better (v2)
... important pass to check usage under limit ... But I wonder how users can see synchronous numbers without tolerance, ... Add, if the sum reaches batch count, we sum and save ... Hmm, maybe I'm misunderstanding. ...
(Linux-Kernel)