File: solve.cal

package info (click to toggle)
apcalc 2.10.3t5.46-1
  • links: PTS
  • area: main
  • in suites: slink
  • size: 4,276 kB
  • ctags: 3,115
  • sloc: ansic: 47,720; makefile: 3,702; awk: 105; sed: 55
file content (47 lines) | stat: -rw-r--r-- 1,174 bytes parent folder | download | duplicates (2)
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
/*
 * Copyright (c) 1995 David I. Bell
 * Permission is granted to use, distribute, or modify this source,
 * provided that this copyright notice remains intact.
 *
 * Solve the equation f(x) = 0 to within the desired error value for x.
 * The function 'f' must be defined outside of this routine, and the low
 * and high values are guesses which must produce values with opposite signs.
 */

define solve(low, high, epsilon)
{
	local flow, fhigh, fmid, mid, places;

	if (isnull(epsilon))
		epsilon = epsilon();
	if (epsilon <= 0)
		quit "Non-positive epsilon value";
	places = highbit(1 + int(1/epsilon)) + 1;
	flow = f(low);
	if (abs(flow) < epsilon)
		return low;
	fhigh = f(high);
	if (abs(flow) < epsilon)
		return high;
	if (sgn(flow) == sgn(fhigh))
		quit "Non-opposite signs";
	while (1) {
		mid = bround(high - fhigh * (high - low) / (fhigh - flow), places);
		if ((mid == low) || (mid == high))
			places++;
		fmid = f(mid);
		if (abs(fmid) < epsilon)
			return mid;
		if (sgn(fmid) == sgn(flow)) {
			low = mid;
			flow = fmid;
		} else {
			high = mid;
			fhigh = fmid;
		}
	}
}

if (config("lib_debug") >= 0) {
    print "solve(low, high, epsilon) defined";
}