-
Notifications
You must be signed in to change notification settings - Fork 0
/
MathOthers.h.cpp
60 lines (56 loc) · 1.23 KB
/
MathOthers.h.cpp
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
52
53
54
55
56
57
58
59
60
#include "MathOthers.h"
#include <math.h>
#include <iostream>
static const double EPS = 1e-8;
double SolveEquationBinarySearch(double(*f)(double), double low, double high)
{
double mid;
while (fabs(f(low)) >= EPS)
{
if (f(low)*f(high) > 0)
break;
mid = (low + high) / 2;
if (f(low)*f(mid) < 0)
high = mid;
else
low = mid;
if (fabs(low - high) < EPS)
break;
}
if (fabs(f(low)) < 1e-4)
return low;
else
return ERROR;
}
double SolveEquationNewton(double(*f)(double), double x)
{
int count = 0;
double last_x;
do
{
count++;
if (count >= MAX_RECURSION_TIMES)
return ERROR;
last_x = x;
x = x - f(x) / Derivative(f, x);
} while (fabs(x-last_x)> EPS);
return x;
}
double Derivative(double(*f)(double), double x, double dx)
{
return (f(x + dx) - f(x)) / dx;
}
double GetArea(int(*curve)(double,double), double up, double down, double left, double right)
{
int count_in_area = 0;
int count_total;
double x, y;
for (count_total = 1; count_total <= AREA_TRY_COUNT; count_total++)
{
x = left + (double)rand() / RAND_MAX*(right - left);
y = down + (double)rand() / RAND_MAX*(up - down);
if (curve(x, y))
count_in_area++;
}
return (double)count_in_area / AREA_TRY_COUNT*(right - left)*(up - down);
}