-1

I'm trying to implement Monte-Carlo method to solve an integral and can't figure an approximation for my function.

double function(double x)
{
    std::complex<double> fz = (pow(-7 * pow(x, 4) - 3 * x + 11, 1.0/3.0) / pow(-2 * pow(x, 6) - 14 * x - 8, 1.0/4.0));
    cout << fz << endl;
    double f = fabs(fz);
    return f;
}

When I substitute 0.25, the approximate result has to be 0.83 - 0.83i (using online calculators) But in my C++ code, it results in 1. What did I do wrong?

The code for approximation:

double integral(unsigned int N)
{
    double sum{}, randomNumber;
    for (unsigned int i = 0; i < N; i++)
    {
        randomNumber = static_cast<double>(rand()) / static_cast<double>(RAND_MAX) / 3;
        sum += function(randomNumber); // estimate function with random value [0; 3]
    }
    return (3 * sum / N);
}
Sebastian
  • 1,834
  • 2
  • 10
  • 22
Suspense
  • 85
  • 1
  • 1
  • 9
  • The C++ code you've shown results in "Variable `x` does not exist", not 1. If you want help with your Monte-Carlo method, you're going to have to show the Monte-Carlo method code, not just a random mathematical function without context – Silvio Mayolo Sep 28 '22 at 22:37
  • Rounding?? Integer division: 1/3, 1/4; should be 1.0/3.0, 1.0/4.0. – Thomas Matthews Sep 28 '22 at 22:38
  • My thought was that there's possibly a bug in your reliance on operator precedence. But your code has no comments to explain what's going on, nor are any of the numerical constants named. If this is an assignment, you will be marked down for that. – Kingsley Sep 28 '22 at 22:52
  • 3
    Please note that, when calling [`std::pow(double x)`](https://en.cppreference.com/w/cpp/numeric/math/pow), *"If base is finite and negative and exp is finite and non-integer, a domain error occurs and a range error may occur."*. [`std::pow(std::complex x)`](https://en.cppreference.com/w/cpp/numeric/complex/pow) returns a complex value instead. – Bob__ Sep 28 '22 at 23:07
  • 1
    Worked, it was pow() method, thanks! – Suspense Sep 28 '22 at 23:14

1 Answers1

1

The problem was with std::pow function. To apply it to complex numbers, the first argument of it must be of complex type:

std::complex<double> numerator(-7 * pow(x, 4) - (3 * x) + 11);
std::complex<double> denumerator(-2 * pow(x, 6) - (14 * x) - 8);
std::complex<double> fz = pow(numerator, third) / pow(denumerator, quarter);
YurkoFlisk
  • 873
  • 9
  • 21
Suspense
  • 85
  • 1
  • 1
  • 9