Anonymous user
Price fraction: Difference between revisions
Ada solution added
(change description to reflect that most of the rescaled values do not fall within the range of values they represent) |
(Ada solution added) |
||
Line 25:
>= 0.96 < 1.01 := 1.00
=={{header|Ada}}==
<lang Ada>
type Price is delta 0.01 digits 3 range 0.0..1.0;
function Scale (Value : Price) return Price is
X : array (1..19) of Price :=
( 0.06, 0.11, 0.16, 0.21, 0.26, 0.31, 0.36, 0.41, 0.46, 0.51,
0.56, 0.61, 0.66, 0.71, 0.76, 0.81, 0.86, 0.91, 0.96
);
Y : array (1..20) of Price :=
( 0.10, 0.18, 0.26, 0.32, 0.38, 0.44, 0.50, 0.54, 0.58, 0.62,
0.66, 0.70, 0.74, 0.78, 0.82, 0.86, 0.90, 0.94, 0.98, 1.0
);
Low : Natural := X'First;
High : Natural := X'Last;
Middle : Natural;
begin
loop
Middle := (Low + High) / 2;
if Value = X (Middle) then
return Y (Middle + 1);
elsif Value < X (Middle) then
if Low = Middle then
return Y (Low);
end if;
High := Middle - 1;
else
if High = Middle then
return Y (High + 1);
end if;
Low := Middle + 1;
end if;
end loop;
end Scale;
</lang>
The solution uses fixed point type to prevent rounding and representation issues. With the above declarations a full coverage test:
<lang Ada>
with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Price_Fraction is
-- Put the declarations here
Value : Price := Price'First;
begin
loop
Put_Line (Price'Image (Value) & "->" & Price'Image (Scale (Value)));
exit when Value = Price'Last;
Value := Price'Succ (Value);
end loop;
end Test_Price_Fraction;
</lang>
Sample output:
<div style="height: 200px;overflow:scroll">
<pre>
0.00-> 0.10
0.01-> 0.10
0.02-> 0.10
0.03-> 0.10
0.04-> 0.10
0.05-> 0.10
0.06-> 0.18
0.07-> 0.18
0.08-> 0.18
0.09-> 0.18
0.10-> 0.18
0.11-> 0.26
0.12-> 0.26
0.13-> 0.26
0.14-> 0.26
0.15-> 0.26
0.16-> 0.32
0.17-> 0.32
0.18-> 0.32
0.19-> 0.32
0.20-> 0.32
0.21-> 0.38
0.22-> 0.38
0.23-> 0.38
0.24-> 0.38
0.25-> 0.38
0.26-> 0.44
0.27-> 0.44
0.28-> 0.44
0.29-> 0.44
0.30-> 0.44
0.31-> 0.50
0.32-> 0.50
0.33-> 0.50
0.34-> 0.50
0.35-> 0.50
0.36-> 0.54
0.37-> 0.54
0.38-> 0.54
0.39-> 0.54
0.40-> 0.54
0.41-> 0.58
0.42-> 0.58
0.43-> 0.58
0.44-> 0.58
0.45-> 0.58
0.46-> 0.62
0.47-> 0.62
0.48-> 0.62
0.49-> 0.62
0.50-> 0.62
0.51-> 0.66
0.52-> 0.66
0.53-> 0.66
0.54-> 0.66
0.55-> 0.66
0.56-> 0.70
0.57-> 0.70
0.58-> 0.70
0.59-> 0.70
0.60-> 0.70
0.61-> 0.74
0.62-> 0.74
0.63-> 0.74
0.64-> 0.74
0.65-> 0.74
0.66-> 0.78
0.67-> 0.78
0.68-> 0.78
0.69-> 0.78
0.70-> 0.78
0.71-> 0.82
0.72-> 0.82
0.73-> 0.82
0.74-> 0.82
0.75-> 0.82
0.76-> 0.86
0.77-> 0.86
0.78-> 0.86
0.79-> 0.86
0.80-> 0.86
0.81-> 0.90
0.82-> 0.90
0.83-> 0.90
0.84-> 0.90
0.85-> 0.90
0.86-> 0.94
0.87-> 0.94
0.88-> 0.94
0.89-> 0.94
0.90-> 0.94
0.91-> 0.98
0.92-> 0.98
0.93-> 0.98
0.94-> 0.98
0.95-> 0.98
0.96-> 1.00
0.97-> 1.00
0.98-> 1.00
0.99-> 1.00
1.00-> 1.00
</pre>
=={{header|AutoHotkey}}==
<lang AutoHotkey>; Submitted by MasterFocus --- http://tiny.cc/iTunis
|