-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtransform.php
56 lines (42 loc) · 1.41 KB
/
transform.php
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
<?php
function continued($x, $terms = 22, $rel_tol = 1e-9, $abs_tol = 0.0) {
// Initialize, using Khinchin's notation
$a = []; // continued fraction terms
$p = [0, 1]; // convergent numerator terms (-2 and -1 indices)
$q = [1, 0]; // convergent denominator terms (-2 and -1 indices)
$s = []; // convergent terms
$remainder = $x;
// Collect the continued fraction and convergent terms
for ($i = 0; $i < $terms; $i++) {
// Compute the next terms
$whole = floor($remainder);
$frac = bcsub($remainder,$whole,20);
$an = (int)$whole;
/*if($i==16){
$an=5;
}*/
$pn = $an * $p[count($p) - 1] + $p[count($p) - 2];
$qn = $an * $q[count($q) - 1] + $q[count($q) - 2];
$sn = [$pn,$qn];
// Add terms to lists
$a[] = $an;
$p[] = $pn;
$q[] = $qn;
$s[] = $sn;
// Convergence check
/* if (is_close($x, floatval($sn), $rel_tol, $abs_tol)) {
break;
}*/
// Get ready for next iteration
$remainder = bcdiv(1,$frac,20);
}
// Return the tuple of the continued fraction and the convergents
return [$a, $s];
}
print_r(continued('1.01964950736352181566869548344827172826353172896898'));
//print_r(continued('0.2312076819339227309219662514224185'));
//536870912
//526524956
//134217728
//131631239
//536870912/134217728