Skip to content

Instantly share code, notes, and snippets.

@bongtrop
Last active December 23, 2015 03:09
Show Gist options
  • Save bongtrop/6571293 to your computer and use it in GitHub Desktop.
Save bongtrop/6571293 to your computer and use it in GitHub Desktop.
Find position
#include <stdio.h>
#include <math.h>
const double ROOT3 = 1.73205080756887729352744634150587236694280525381;
double f(double x) {
return (x*x - 3);
}
double df(double x) {
return (2 * x);
}
int swap(double *a, double *b) {
int tmp = *a;
*a = *b;
*b = tmp;
return 0;
}
//Usage: newton(ค่าเริ่มต้น, จำนวนครั้ง, ฟังชั้น, อนุพันธ์พังชั้น);
//Return: ตำแหน่ง x ใกล้ 0
double newton(double start, int n, double fc(double x), double dfc(double x)) {
double x = start, error;
int sign;
if (fc(start) > 0.0) {
sign = -1;
}
else {
sign = 1;
}
for (int i = 0; i <= n; i++){
x = x + (fc(x) / dfc(x))*sign;
error = ROOT3 - x;
printf("x = %.16f\n", x);
printf("log|error| = %.16f\n", log10(fabs(error)));
}
return x;
}
//Usage: newton(ค่าด้านซ้าย, ค่าด้านขวา, จำนวนครั้ง, ฟังชั้น);
//Return: ตำแหน่ง x ใกล้ 0
double bisection(double a, double b, int n, double fc(double x)) {
double check, error;
if (a > b) {
swap(&a, &b);
}
for (int i = 0; i <= n; i++) {
check = (a + b) / 2;
if (fc(check) >= 0) {
b = check;
}
else {
a = check;
}
error = ROOT3 - check;
printf("x = %.16f\n", check);
printf("log|error| = %.16f\n", log10(fabs(error)));
}
return check;
}
int main(int argc, char *argv []) {
printf("Newton Method Test\n");
newton(3.0, 10, f, df);
printf("\nbisection Method Test\n");
bisection(1.0, 3.0, 10, f);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment