Debian Codegraph @

test/mpfrsqrt.awk

raw
1 # Date: Sat, 02 Aug 2014 12:27:00 -0400
2 # To: [email protected]
3 # From: Katherine Wasserman <[email protected]>
4 # Message-ID: <[email protected]>
5 # Subject: [bug-gawk] GAWK 4.1 SQRT() bug
6 #
7 # In version 4.1.60 of GAWK the sqrt() function does not work correctly on bignums.
8 # Here's a demo of the problem along with, a function that does work correctly.
9 #
10 # Running this program (sqrt-bug.awk):
11 # --------------------------------------------------------------------
12
13 @load "intdiv"
14 BEGIN {
15 a=11111111111111111111111111111111111111111111111111111111111
16 print sqrt(a^2)
17 #print sq_root(a^2)
18
19 # ADR: Added for gawk-4.1-stable which doesn't have built-in intdiv() function
20 if (PROCINFO["version"] < "4.1.60")
21 print sq_root2(a^2)
22 else
23 print sq_root(a^2)
24 }
25
26
27 function sq_root(x, temp,r,z)
28 { temp=substr(x,1,length(x)/2) + 0 # a good first guess
29 z=0
30 while (abs(z-temp)>1)
31 { z=temp
32 intdiv(x,temp,r)
33 temp=r["quotient"] + temp
34 intdiv(temp,2,r)
35 temp=r["quotient"]
36 }
37 return temp
38 }
39
40 function sq_root2(x, temp,r,z)
41 { temp=substr(x,1,length(x)/2) + 0 # a good first guess
42 z=0
43 while (abs(z-temp)>1)
44 { z=temp
45 awk_div(x,temp,r)
46 temp=r["quotient"] + temp
47 awk_div(temp,2,r)
48 temp=r["quotient"]
49 }
50 return temp
51 }
52
53 function abs(x)
54 { return (x<0 ? -x : x)
55 }
56 #
57 # --------------------------------------------------------------------
58 # gawk -M -f sqrt-bug.awk
59 #
60 # results in:
61 # 11111111111111111261130863809439559987542611609749437808640
62 # 11111111111111111111111111111111111111111111111111111111111
63 #
64 # Thanks,
65 # Katie
66 #
67
68 # div --- do integer division
69
70 function awk_div(numerator, denominator, result, i, save_PREC)
71 {
72 save_PREC = PREC
73 PREC = 400 # good enough for this test
74
75 split("", result)
76
77 numerator = int(numerator)
78 denominator = int(denominator)
79 result["quotient"] = int(numerator / denominator)
80 result["remainder"] = int(numerator % denominator)
81
82 PREC = save_PREC
83 return 0.0
84 }