Hi there,

The Wallis product is defined here: http://en.wikipedia.org/wiki/Wallis_product

I am having a problem with the following code, which attempts to approximate the product:

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int n = 2;  // initialise top counter as 2 for the first two terms
    int x = 1;  // initialise bottom counter as 1 for the first term
    float Answer = 1;

    // calculate the value for pi/2 using a for loop
    for ( n ; n <= 1000; n += 2 )
    {
        Answer = Answer * ( (n*n) / ( x * (x + 2) ) );
        x += 2;
    }

    cout << "The approximated value for pi/2 = " << Answer << endl;
    cout << "The theoretical value for pi/2 = " << M_PI/2 << endl;

    return 0;
}

My problem is that I always get a 1 (what I initialised it to) for the ouput of the approximated value. Where is my mistake?

Thanks :)

n and x need to be floats (or better yet make everything doubles).

n and x need to be floats (or better yet make everything doubles).

Thanks :) It seems to work. Why is this the case though? The counters n and x never use floating point numbers, but only integers. Isn't it only the "Answer" that using a float?

It's because of integer division.
For two floats, 1.0 / 2.0 is 0.5.
For two ints, 1 / 2 is 0, thowing the fractional part away (and no rounding).
Actaully, you can leave n and x as int's if you cast at least one of the division operands to a float:

for ( n = 2; n <= 1000; n += 2 )
    {
        Answer = Answer * ( (float)(n*n) / ( x * (x + 2) ) );
        x += 2;
    }

I see a few items that you may want to look at.

First, I would recommend using double instead of float.

Secondly, M_PI/2 is not defined.

I also see that your parenthesis are not paired in the for statement. I believe that you may want to omit the open left parenthesis after the division.

Good Luck!!!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.