| 1 |
function abs(x) { |
| 2 |
return (x+0 >= 0) ? x : -x |
| 3 |
} |
| 4 |
|
| 5 |
function check(x,what, f,res) { |
| 6 |
for (f in formats) { |
| 7 |
res = sprintf(f,x) |
| 8 |
if (formats[f] == "non-decimal") { |
| 9 |
if ((x >= 0) && (res !~ /e+/)) { |
| 10 |
if (abs(strtonum(res)-x) > 1e-5*abs(x)) |
| 11 |
printf "(sprintf(%s,%s) = %s)-%g = %g\n", |
| 12 |
f,what,res,x,strtonum(res)-x |
| 13 |
} |
| 14 |
} |
| 15 |
else if (abs(res-x) > 1e-5*abs(x)) |
| 16 |
printf "(sprintf(%s,%s) = %s)-%g = %g\n", |
| 17 |
f,what,res,x,res-x |
| 18 |
} |
| 19 |
} |
| 20 |
|
| 21 |
function check_cons(fmt,base,rot,mexp, i,j,dig,res,s) { |
| 22 |
# first off, check that zero formats properly |
| 23 |
if ((s = sprintf(fmt,0)) != "0") |
| 24 |
printf "(sprintf(%s,0) = %s) != 0\n",fmt,s |
| 25 |
|
| 26 |
res = "1" |
| 27 |
dig = 1 |
| 28 |
j = 0 |
| 29 |
for (i = 0; i <= mexp; i++) { |
| 30 |
s = sprintf(fmt,base^i) |
| 31 |
if (s ~ /e+/) |
| 32 |
return |
| 33 |
if (s != res) |
| 34 |
printf "(sprintf(%s,%d^%d) = %s) != %s\n", |
| 35 |
fmt,base,i,s,res |
| 36 |
if (++j == rot) { |
| 37 |
dig = 1 |
| 38 |
res = ("10"substr(res,2)) |
| 39 |
j = 0 |
| 40 |
} |
| 41 |
else { |
| 42 |
dig *= 2 |
| 43 |
res = (dig substr(res,2)) |
| 44 |
} |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
BEGIN { |
| 49 |
# this doesn't necessarily have to be exact since we're checking |
| 50 |
# magnitude rather than precision |
| 51 |
if (!HUGEVAL) HUGEVAL = 1.7976931348623157e+308 |
| 52 |
|
| 53 |
formats["%s"] = "" |
| 54 |
formats["%d"] = "" |
| 55 |
formats["%.0f"] = "" |
| 56 |
formats["0%o"] = "non-decimal" |
| 57 |
formats["0x%x"] = "non-decimal" |
| 58 |
|
| 59 |
check(0,"0") |
| 60 |
limit = HUGEVAL / 10 |
| 61 |
value = 1 |
| 62 |
for (i = 0; ; i++) { |
| 63 |
check(10^i,"10^"i) |
| 64 |
check(-10^i,"-10^"i) |
| 65 |
#[probably should test value against 10^i here] |
| 66 |
if (value >= limit) break |
| 67 |
value *= 10 |
| 68 |
} |
| 69 |
limit = HUGEVAL / 2 |
| 70 |
value = 1 |
| 71 |
for (i = 0; ; i++) { |
| 72 |
check(2^i,"2^"i) |
| 73 |
check(-2^i,"-2^"i) |
| 74 |
#[probably should test value against 2^i here] |
| 75 |
if (value >= limit) break |
| 76 |
value *= 2 |
| 77 |
} |
| 78 |
|
| 79 |
check_cons("%d",10,1,9) |
| 80 |
check_cons("%x",2,4,31) |
| 81 |
check_cons("%o",2,3,31) |
| 82 |
|
| 83 |
# make sure basic %d and %x are working properly |
| 84 |
printf "%d %d %x\n",3.7,-3.7,23.7 |
| 85 |
|
| 86 |
# check another problem in gawk 3.1.5: precision over 30 crashes |
| 87 |
printf "%.55d\n",1 |
| 88 |
} |