Why do some insignificant parentheses change the answer?

  • 0
    I wrote a program that was supposed to calculate a recursive formula.
    My answers did not agree. I decided to remove some brackets and everything worked out.
    Explain, please, what is the difference between the 1st formula and the 2nd?
    Why is there one answer according to the first formula, and another according to the second?
    Could the problem be with the priority of operations?

    1) a = a * (-x) * (2 * i + 1) / (2 * i);
    2) a = a * (-x) * ((2 * i + 1) / (2 * i));

    The value according to the control formula should be equal to the sum, taking into account the error.
    C ++ language:
    #include <iostream>
    #include <stdio.h>
    #include <math.h>
    
    using namespace std;
    
    int main()
    {
        double s,x,e,a,y;
        int i = 1;
        cout<<"Аргумент: "<<endl;
        cin>>x;
        cout<<"Погрешность: "<<endl;
        cin>>e;
    
        a = 1;
        s = a;
        y= 1/sqrt(pow((1+x),3));
    
        while(e <= abs(a))
        {
            a = a *(-1*x)*((2*i+1)/(2*i));
            s +=a;
            i++;
        }
    
        cout<<"Сумма ряда"<<endl;
        cout<<s<<endl;
        cout<<"Контрольная формула "<<endl;
        cout<<y;
    
        return 0;
    }
    C++ Blake Nunez, Oct 12, 2020

  • 2 Answers
  • 0
    (- x) * (2 * i + 1) / (2 * i) - a real number is multiplied by an integer, the result is real, then the real number is divided by a real, the result is real.

    (- x) * ((2 * i + 1) / (2 * i)) - an integer divided by an integer, the result is an integer , then a real number is multiplied by an integer, the result is real.
    Juliette Santos

  • 0
    You have i - integer, and x - real. When dividing a whole by a whole, division is performed entirely (with rounding down to the whole). When dividing a whole by a real or a real by a whole, the result is real.



    If you put extra brackets, then you first have an integer division (2 * i + 1) / (2 * i) , and then multiply by a real one.

    Without parentheses, operations are performed from left to right - a * (- 1 * x) * (2 * i + 1) will give a real result that is exactly divisible.



    If you lead to a real in parentheses, then everything will work for you too: a = a * (- 1 * x) * ((2 * i + 1.0) / (2 * i));
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!