-
Notifications
You must be signed in to change notification settings - Fork 0
/
list8-8.c
51 lines (42 loc) · 1.28 KB
/
list8-8.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/* 方程式の解を求める */
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
/* 解析したい関数 */
double func(double x)
{
return x * x * x * x * x - 10.0 * x * x * x * x + 25.0 * x * x * x + 40.0 * x * x + 200.0 * x - 500.0;
}
/* 2文探索法(バイナリサーチ) */
double BinarySearch(void)
{
double left, mid, right, epsilon;
/*
* 答えに非常に近いという範囲を定義する。
* この値をいろいろとかえることで、答えの精度を調節できる。
* ちなみに、あまり小さくしすぎると情報落ちの関係で
* 答えが求まらなくなってしまうので注意。
*/
epsilon = 0.00001;
/* leftとrightの間に確実に解がある、という範囲を指定する */
left = 1.0;
right = 3.0;
/* 範囲をひたすら絞り込む */
while(fabs(right-left) > epsilon && fabs(func(left)) > epsilon){
mid = (left+right) / 2.0;
/* func(left)とfunc(mid)が同じ符号なら */
if(func(left) * func(mid) >= 0.0){
left = mid; /* leftの位置をmidにあわせる */
}else{
right = mid; /* rightの位置をmidにあわせる */
}
}
return left;
}
int main(void)
{
double d;
d = BinarySearch();
printf("方程式の解は%1f. そのときのfunc(x)は%1fです。\n", d, func(d));
return 0;
}