calculation problem

Im having calculating the right value for the 2.5 input, the function is the problem but I don't know where the problem in my calculation is. The outcome is supposed to be 12.18249396 but i comes out short.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 
float seq(float exp)
{
      float prev(0.0),atol(0.0),icnt(1.0);
       
      prev = 1.0 + (1.0 * exp/icnt);// begin of sequence
      do
      {
          icnt++; // next sequence
          prev = prev * (exp/icnt);//get total to add
          atol = atol + prev;// pools the additions
             
      }
      while(prev > 0);// condition 
      
      return atol;      //total value of pool
}
/*Test data

Input the number to do convergence sequence:
2.5
convergence total is: 12.155492
Press any key to continue . . .*/      
      
Last edited on
Replace line 6
 
    prev = 1.0 + (1.0 * exp/icnt);// begin of sequence 

with:
1
2
    prev = exp / icnt;             // begin of sequence
    atol = 1.0 + prev;             // begin of sequence    


By the way, in main() you were calling the function twice, which is unnecessary.
Thank you, Chervil

Feeling real dumb right now, but not down. I didn't see that.
But Thank you for your help, means a lot.
No problem.

By the way, using this to terminate the loop is probably inefficient:
while(prev > 0);// condition

If you insert an integer counter to see how many times the loop executes, it may be about 50 times.

However - change the type from float to double and it increases to about 200 times. Use long double and it loops about 2000 times.

There are better ways...
Last edited on
Topic archived. No new replies allowed.