#include <stdio.h>
#include <math.h>

#define EPS 1e-5

// Function
double f(double x) {
    return x*x - 1 - sin(x);
}

// Bisection Method (二分法)
double bisection(double a, double b, int *iterations) {
    double mid;
    *iterations = 0;

    while (1) {
        (*iterations)++;
        mid = (a + b) / 2.0;

        if (fabs(f(mid)) < EPS) return mid;

        if (f(a) * f(mid) < 0)
            b = mid;
        else
            a = mid;
    }
}

// False Position Method (はさみうち法)
double false_position(double a, double b, int *iterations) {
    double x;
    *iterations = 0;

    while (1) {
        (*iterations)++;
        x = (a * f(b) - b * f(a)) / (f(b) - f(a));

        if (fabs(f(x)) < EPS) return x;

        if (f(a) * f(x) < 0)
            b = x;
        else
            a = x;
    }
}

int main() {
    double r1, r2;
    int it1, it2;

    printf("========================================\n");
    printf(" Solving f(x) = x^2 - 1 - sin(x) = 0\n");
    printf("========================================\n");

    // ---- Bisection ----
    printf("\n[ Bisection Method ]\n");

    r1 = bisection(-1.0, 0.0, &it1);
    printf("Interval [-1,0]: Root = %.6f, Iterations = %d\n", r1, it1);

    r2 = bisection(1.0, 2.0, &it2);
    printf("Interval [1,2]: Root = %.6f, Iterations = %d\n", r2, it2);

    // ---- False Position ----
    printf("\n[ False Position Method ]\n");

    r1 = false_position(-1.0, 0.0, &it1);
    printf("Interval [-1,0]: Root = %.6f, Iterations = %d\n", r1, it1);

    r2 = false_position(1.0, 2.0, &it2);
    printf("Interval [1,2]: Root = %.6f, Iterations = %d\n", r2, it2);

    return 0;
}