DEV Community

Discussion on: Write a simple function (C++) program that checks the identity : cos 2x = 2cos2x –1.

Collapse
stevesims2 profile image
SteveSims2 • Edited
#include <iostream>
#include <string>
int main()
{
    std::string message = "PASSED: All values checked were equal.";

    for (double x = -10; x < 10; x += 0.1)
    {
        double left = cos(2 * x);
        double right = (2 * cos(x) * cos(x)) - 1;

        //Set precision of left and right to prevent underflow
        left = round(left * 10000000.0) / 10000000.0;
        right = round(right * 10000000.0) / 10000000.0;

        if (left != right) {
            message = "FAILED: The two values are not equal: " + std::to_string(left) + "!=" + std::to_string(right);
            break;
        }
    }
    std::cout << message;
}
Enter fullscreen mode Exit fullscreen mode