0

I'm trying to get an if statement to terminate the program when the limit for a convergent sequence is met, in this case 3+(1/k^2) = 3.

#include <iostream>
#include <math.h>

int findK(int k)
{
        double x = 0;
        for(double i=2;i<k;i++)
        {
                x = (1/pow(i, 2)+3);
                if(std::fmod(x, 1.0) == 0)
                {
                        std::cout << "Sequence terminated at, " << i << "th term.\n";               
                        exit(0);
                }
                else
                {
                        std::cout << x;
                }
                if(i != k-1) std::cout << ", ";
        }
        std::cout << std::endl;
}

int main()
{
        int n = 453;
        findK(n);

        return 0;
}

I am not the best at maths or programming/c++ but it appears to me as though once the sequence hits 3, the if statement doesn't trigger. When I replace x = (1/pow(i, 2)+3) with x = 3. Then the if statement runs and terminates the program. Am I missing something here? Please let me know in dummy terms if you can.

milkdose
  • 15
  • 4

2 Answers2

1

The problem here is that you are hoping an infinite sequence will converge. What you should do is loop until it is almost zero, not zero exactly, using std::numeric_limits<double>::epsilon() for instance, giving us this code - I added printing out of the std::fmod() result each time round the loop so you can see what is happening:

#include <iostream>
#include <cmath>
#include <limits>

int findK(int k)
{
        double x = 0;
        for(double i=2;i<k;i++)
        {
                x = (1/pow(i, 2)+3);
                if(std::fmod(x, 1.0) <= std::numeric_limits<double>::epsilon())
                {
                        std::cout << "Sequence terminated at, " << i << "th term.\n";               
                        exit(0);
                }
                else
                {
                        std::cout << x << "; " << std::fmod(x, 1.0) << ", ";
                }
                if(i != k-1) std::cout << ", ";
        }
        std::cout << std::endl;
}

int main()
{
        int n = 453;
        findK(n);

        return 0;
}

This is the code on ideone.com, but it doesn't converge before it runs out of processor time...

Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
1

Because double has precision of about 16 decimals, you need to pass n=100000000 to findK for the expression to converge. Of course, you should remove std::cout<<x from the program to make it reasonably fast.

Eugene
  • 6,194
  • 1
  • 20
  • 31