integral calculation, discrete mathematics

I need to calculate the integral. The area G bounded by the circle x[SUP]2 [/SUP]+y[SUP]2[/SUP]enter a description of the image here

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

int main()
{
    srand(5234);
    int n = 1000000;
    int a = 5;
    float summa = 0;
    float area_d = 4 * pow(a, 2);

    for (int i = 1; i <= n; i++) {
        float x = rand() % a;
        float y = rand() % a;
        if (pow(x, 2) + pow(y, 2) <= pow(a, 2)) {
            summa+=1/(sqrt(24+pow(x,2)+pow(y,2)));
        }
    }

    cout << "For n = " << n << " experimentov i  a = " << a << " polucili integral = " << (1. / n) * area_d * summa;
    return 0;
}
Author: Igor, 2020-11-17

1 answers

Well, we can say that in some sense this is an error. But seriously.. You generate only integer coordinates float x = rand() % a; - what accuracy can we talk about? Well, as you correctly noted in the comments, you must have coordinates from -a to a. Also, why do you use the pow() function for banal squaring? This, at least, greatly impairs the readability of the code. And in the worst case, if the compiler does not know how to recognize such constructs, then to slower ones calculations.

Here is a slightly tweaked code (answer: 13.2103):

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

int main()
{
    srand(5234);
    int n = 1000000;
    int a = 5;
    double summa = 0;
    double area_d = 4 * a * a;

    for (int i = 1; i <= n; i++) {
        double x = 2.0 * rand()/RAND_MAX * a - a;   // от -a до a
        double y = 2.0 * rand()/RAND_MAX * a - a;   // от -a до a
        if (x*x + y*y <= a*a) {
            summa += 1.0/(sqrt(24+x*x+y*y));
        }
    }

    cout << "For n = " << n << "\nexperimentov i  a = " << a << "\npolucili integral = " << (1. / n) * area_d * summa << "\n";
    return 0;
}
 2
Author: Vladimir, 2020-11-17 20:15:08