Monte Carlo help

I am having trouble on one of my problems for my C++ class. The trouble is that I don't really understand how to use random numbers and such.

The problem is to use the Monte Carlo method to estimate the integral of fx=2x^2+3x-2.

1)Pass the function the total numbers of darts to be thrown (q).
2)For each dart thrown generate two random numbers, x from a to b, and y from 0 to m, and consider the point (x,y) as being where the darts hit.
3)Determine if the point lies under the curve or not. If it does, increment p.
4)After all darts have been thrown, compute the area using the equation: p/q=(area under curve)/(area of rectangle)

This is what I have so far:

#include<iostream>
using namespace std;

#include<cstdlib>
#include<ctime>
#include<iomanip>

double monte(int q, int m);

int main()
{
int q, m;
double qfx;

cout<<"Enter the number of darts to be thrown: ";
cin>>q;

cout<<"Enter the maximum height: ";
cin>>m;

srand(time(NULL));

qfx=monte(q, m);

cout<<"For "<<q<<" darts thrown, the value of fx is "<<qfx<<endl;

return 0;
}

double monte(int q, int m)
{
int i, p=0;
double qfx;

for(i=1; i<=q; i++)
{
double x, y, fx;
int a=2, b=8;
x=static_cast<double>(rand()%(a*(b-a)));
y=static_cast<double>(rand()%(m+1));

fx=((2*(x*x))+(3*x)-2);

if(p<=fx)
p++;
}
qfx=static_cast<double>(p)/q;
return qfx;
}


Thanks a bunch!
Ryan
This looks like it should be working OK...I think there might be an error in determining the answer in your monte() function by using p / q alone (your description says p/q = integral area/rectangle area, so there's one more piece of algebra to be done), but codewise, this should be fine.

So what's the problem?
if x needs to be between a and b, then this line isn't correct:
 
x=static_cast<double>(rand()%(a*(b-a)));

That creates a number between 0 and (ab - a^2 -1).

If you want a to b inclusive, try this:
 
x = (rand()%(b + 1 - a)) + a;
Thanks guys! I managed to figure it out on my own. If anyone wants the finished code I can post it up.
Topic archived. No new replies allowed.