Caroline
Caroline

Reputation: 1

How can I increase my code's robustness and efficiency to calculate limit

I have written a code to compute the limit of the following series:
Un+1 = Un - MyFunction1(Un)/MyFunction2(Un)

Is there a way I could modify my code to increase its robustness and efficiency? I was thinking of maybe adding a Try Catch statement to check if the denominator is zero instead. But not sure if that is the right thing to do. Any other suggestions?

conditions given to me are:

  1. dConstant equal to 5.0 when invoking the functions
  2. Initial value of Un (where n is zero) = 10
  3. A maximum of 30 iterations
  4. At each step, a test is performed on the absolute value of the difference Un+1 - Un which must be smaller than an error of 0.1

The following two functions used in the code are assumed to be from a library:
extern double MyFunction1(double x, double dConstant) ;
extern double MyFunction2(double x, double dConstant) ;

#include <iostream>
#include <math.h>
int main(){
   int i=0;
   double dU0=10.0;
   double dU1=0.0;
for (i=0 ; i<30 ; i++) {
   if(MyFunction2 (dU0,5.0) != 0.0) {
      dU1 = dU0 - MyFunction1(dU0,5.0)/ MyFunction2(dU0,5.0);
    }
   if (fabs(dU1 - dU0)<0.1){
      break;
   }
   dU0=dU1;
}
   if (i<30){
      std::cout<< "The result of the series is: " << dU1 << '\n';
   }
   else{
     std::cout<< "The series does not converge\n";
   }
return 0;
}

Upvotes: 0

Views: 62

Answers (1)

ThivinAnandh
ThivinAnandh

Reputation: 286

Checking whether divisor is Zero

Computationally speaking , you are not supposed to compare a difference between floating point value to numerical zero 0 because of the limits in machine precision. It is always bets compare your results to be within a tolerance of very small number. Like

fabs(dU1 - dU0)<1e-10

This always puts you on safer side because, of the number is very close to machine precision 1e-308 ( depending on your machine ), it still wont be represented as a proper zero. Further, division by this very small number can also blow up your result.

Break

its not a big optimisation however, You can avoid the break inside the code by making that check in the for loop itself for (i=0 ; i<30 && fabs(dU1 - dU0)<1e-10; i++)

Macros

given your function is very small like `x2 + 5x + 6', then you could write a macro for the same which would avoid the function calls at each iteration during run time. the macros will replace the values at compile time itself there by reducing runtime load.

#define  MyFunction2(x,y) x*x - 5*x + 6
#define  MyFunction1(x,y) 2*x - 5

Upvotes: 1

Related Questions