#include "stdafx.h" #include #include #define e 0.0001 double f(double x) { return x*x*x - 8*x*x + 4; } double f1(double x) { return 3*x*x - 16*x; } double BinarySearch(double a, double b) { int count = 1; double c; while(true) { if (b-a >2*e) { c = (a+b)/2; if (f(a)*f(c) >0) { a = c; } else { b = c; } count++; } else { printf("i = %d\t", count); return (a+b)/2; } } } double NewtonMethod(double a, double b) { double x = (a+b)/2; x -= f(x) / f1(x); int count = 1; while (true) { if(abs(f(x)) > e) { x -= f(x) / f1(x); count++; } else { printf("i = %d\t", count); return x; } } } int main() { double x; printf("f(x) = x^3 - 8*x^2 + 2\n"); printf("Binary search\n"); printf("[-1, -0.5]: x = %f, f(x) = %.10f \n", x = BinarySearch(-1, -0.5), f(x)); printf("[0.5, 1]: x = %f, f(x) = %.10f \n", x = BinarySearch(0.5, 1), f(x)); printf("[7, 9]: x = %f, f(x) = %.10f \n", x = BinarySearch(7, 9), f(x)); printf("Newton method\n") ; printf("[-1, -0.5]: x = %f, f(x) = %.10f \n", x = NewtonMethod(-1, -0.5), f(x)); printf("[0.5, 1]: x = %f, f(x) = %.10f \n", x = NewtonMethod(0.5, 1), f(x)); printf("[7, 9]: x = %f, f(x) = %.10f \n", x = NewtonMethod(7, 9), f(x)); return 0; }