summaryrefslogtreecommitdiffstats
path: root/lib/Math/Decimal/FastPP.pm
blob: 538fb9230af6b400e98d48a70526952e73227dde (plain)
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package Math::Decimal::FastPP;

use strict;
use warnings;

use Exporter qw(import);
our @EXPORT_OK = qw(dadd dmul drhtz drhfz);

our $VERSION = '0.001';

sub dadd
{
	my ($ai, $af) = split(/[.]/, $_[0]);
	my ($bi, $bf) = split(/[.]/, $_[1]);
	$af ||= '';
	$bf ||= '';
	my $ae = length($af);
	my $be = length($bf);
	my $ce;
	if ($ae == $be) {
		$ce = $ae;
	} elsif ($ae < $be) {
		$af .= '0' x ($be - $ae);
		$ce = $be;
	} else {
		$bf .= '0' x ($ae - $be);
		$ce = $ae;
	}
	my $as = $ai . $af;
	my $bs = $bi . $bf;
	my $cs = $as + $bs;
	$cs = sprintf("%0${ce}i", $cs);
	return
		substr($cs, 0, length($cs) - $ce) . '.' .
		substr($cs, length($cs) - $ce);
}

sub dmul
{
	my ($ai, $af) = split(/[.]/, $_[0]);
	my ($bi, $bf) = split(/[.]/, $_[1]);
	$af ||= '';
	$bf ||= '';
	my $as = $ai . $af;
	my $ae = length($af);
	my $bs = $bi . $bf;
	my $be = length($bf);
	my $cs = $as * $bs;
	my $ce = $ae + $be;
	$cs = sprintf("%0${ce}i", $cs);
	return
		substr($cs, 0, length($cs) - $ce) . '.' .
		substr($cs, length($cs) - $ce);
}

sub drhtz
{
	my ($ai, $af, $ad) = $_[0] =~ m/^(-?\d*)[.](\d{$_[1]})(\d*)$/ or return;
	my $as = $ai . $af;
	if ($as >= 0) {
		if ($ad > '5' . '0' x (length($ad) - 1)) { ++$as; }
	} else {
		if ($ad > '5' . '0' x (length($ad) - 1)) { --$as; }
	}
	$as = sprintf("%0$_[1]i", $as);
	return
		substr($as, 0, length($as) - $_[1]) . '.' .
		substr($as, length($as) - $_[1]);
}

sub drhfz
{
	my ($ai, $af, $ad) = $_[0] =~ m/^(-?\d*)[.](\d{$_[1]})(\d*)$/ or return;
	my $as = $ai . $af;
	if ($as >= 0) {
		if ($ad >= '5' . '0' x (length($ad) - 1)) { ++$as; }
	} else {
		if ($ad >= '5' . '0' x (length($ad) - 1)) { --$as; }
	}
	$as = sprintf("%0$_[1]i", $as);
	return
		substr($as, 0, length($as) - $_[1]) . '.' .
		substr($as, length($as) - $_[1]);
}

1;

__END__

=head1 NAME

Math::Decimal::FastPP - Fast pure-Perl decimal math

=head1 VERSION

0.001

=head1 SYNOPSIS

	use Math::Decimal::FastPP qw(dadd dmul drhtz drhfz);

	$a = dadd($a, "1.23");  # $a += 1.23
	$c = dmul($a, $b);      # $c = $a * $b
	$a = drhtz($a);         # Round half toward zero

=head1 DESCRIPTION

Math::Decimal::FastPP provides a few common decimal arithmetic and rounding
functions written in pure Perl.  The functions are of course slower than Perl's
built-in binary floating-point math, but they're faster than
L<Math::BigFloat|Math::BigFloat> and other commonly used decimal math modules.

This module is currently less complete than Perl's built-in math and other
decimal math modules.  So far it only includes addition, multiplication, and two
rounding functions.

Despite the similar name and purpose, this module is not compatible with
L<Math::Decimal|Math::Decimal>.

=head1 PHILOSOPHY

This module is designed both to run fast and to be used fast.  The functions are
written to be as short and fast as possible, at a small cost in readability.
For help reading the bodies of these functions, see L</THEORY> below.

The names and parameters of this module's functions are kept minimal to allow
them to be typed quickly and to take little space in calling code.  After all, a
function to add two numbers shouldn't take much more typing than C<+>.  The
names of the rounding functions may look strange, but they are simply
initialisms (or acronyms, if you're creative enough) of "decimal round toward
zero" and "decimal round (away) from zero".

=head1 THEORY

The binary operation functions (C<dadd()> and C<dmul()>) operate on two numbers,
C<a> and C<b>.  And obviously the unary operation functions (C<drhtz()> and
C<drhfz()>) operate on one number, C<a>.  The binary operation functions produce
a resulting number, C<c>.

The input numbers C<a> and C<b> are broken into their integer (C<i>) and
fractional (C<f>) parts, for example C<$ai> and C<$af>.  All three numbers C<a>,
C<b>, and C<c> are comprised of a significand C<s> and (negated) exponent C<e>
and can be expressed as C<s * 10**(-1*e)>.

The significand is all of the significant digits (although the digits are
preserved exactly as given, so leading zeroes are considered "significant") in
the form of an integer, with no radix point.  It is formed simply by
concatenating the integer and fractional parts, e.g. C<$as = $ai . $af>.  The
exponent is simply the number of digits in the fractional part, e.g.
C<$ae = length($af)>.

Multiplication is done simply be multiplying the integer significands and adding
the exponents.  The resulting significand and exponent is converted back into a
string with integer and fractional parts.

Addition is a little more complicated.  The exponents of the two input numbers
must match; if they don't, zeroes are appended to the significand of the number
with the smaller exponent to make the exponents match.  The significands are
then added.  The output number is converted from the resulting significand and
the common exponent of the input numbers.

=head1 SUBROUTINES/METHODS

=head2 dadd()

	$c = dadd($a, $b);

Adds C<$a> and C<$b> and returns their sum.

=head2 dmul()

	$c = dmul($a, $b);

Multiplies C<$a> and C<$b> and returns their product.

=head2 drhtz()

	$a = drhtz($a, $p);

Rounds C<$a> with precision C<$p>.  Halves are rounded toward zero.  For
example:

	drhtz("23.5", 0);   # Returns "23."
	drhtz("2.35", 1);   # Returns "2.3"
	drhtz("-23.5", 0);  # Returns "-23."
	drhtz("-2.35", 1);  # Returns "-2.3"

C<$p> is a non-negative (i.e. zero or positive) integer representing the number
of significant digits right of the radix point.

=head2 drhfz()

	$a = drhfz($a, $p);

Rounds C<$a> with precision C<$p>.  Halves are rounded away from zero.  For
example:

	drhfz("23.5", 0);   # Returns "24."
	drhtz("2.35", 1);   # Returns "2.4"
	drhfz("-23.5", 0);  # Returns "-24."
	drhtz("-2.35", 1);  # Returns "-2.4"

C<$p> is a non-negative (i.e. zero or positive) integer representing the number
of significant digits right of the radix point.

=head1 DIAGNOSTICS

This module has no diagnostics.

=head1 CONFIGURATION AND ENVIRONMENT

This module has no configuration and is not affected by the environment.

=head1 DEPENDENCIES

This module does not depend on any modules outside of the standard distribution
of Perl.

=head1 INCOMPATIBILITIES

Despite the similar name and purpose, this module is not compatible with
L<Math::Decimal|Math::Decimal>.

=head1 BUGS AND LIMITATIONS

These arithmetic functions preserve all significant fractional digits, including
trailing zeroes.  They also don't always add a leading zero before the radix
point for numbers with absolute values less than one.  So the output numbers can
look "ugly", like ".123000".  This is only an issue if the numbers (which are
returned as strings) are concatenated into other strings or printed without
formatting.  If this is an issue in your code, use the outputs as numbers (e.g.
C<$c + 0>) or print with formatting (with C<printf>).

=head1 AUTHOR

Patrick McDermott L<mailto:patrick.mcdermott@libiquity.com>

=head1 SEE ALSO

L<Math::BigFloat|Math::BigFloat>, L<Math::Decimal|Math::Decimal>

=head1 LICENSE AND COPYRIGHT

Copyright (C) 2017  Patrick McDermott

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see L<http://www.gnu.org/licenses/>.