Math-Utils-1.14000755001750001750 013647634102 13621 5ustar00jgamblejgamble000000000000Math-Utils-1.14/Build.PL000555001750001750 165213647634102 15261 0ustar00jgamblejgamble000000000000use Module::Build; use strict; use warnings; my $build = Module::Build->new( module_name => 'Math::Utils', dist_abstract => 'Useful mathematical functions not in Perl', dist_author => ['John M. Gamble '], dist_version => '1.14', dist_name => 'Math-Utils', requires => { perl=> '5.10.1', }, configure_requires => { 'Module::Build' => '0.4', }, build_requires => { 'Test::More' => 0 }, license => 'perl', create_license => 1, create_readme => 0, create_makefile_pl => 'traditional', dynamic_config =>0, meta_merge => { keywords => [ qw(math math-utils sign gcd logarithm scale softmax comparison polymonial) ], resources => { repository => 'git://github.com/jgamble/Math-Utils.git', # repository => { # url => 'git://github.com/jgamble/Math-Utils', # web => 'https://github.com/jgamble/Math-Utils', # type => 'git', # }, }, }, ); $build->create_build_script; Math-Utils-1.14/CONTRIBUTING.md000444001750001750 107613647634102 16213 0ustar00jgamblejgamble000000000000# HOW TO REQUEST CHANGES, FIXES, OR NEW FEATURES The CPAN author does not lack for sites that offer ways to support their modules. If you have found a bug or need an improvement, please make the request at one of these two sites: RT, CPAN's request tracker, is the oldest and most established. It is probably best for reporting true bugs. [RT for Math-Utils](http://rt.cpan.org/NoAuth/Bugs.html?Dist=Math-Utils) This module is developed with github, and issues may be presented and discussed there. [Github link for Math-Utils](https://github.com/jgamble/Math-Utils) Math-Utils-1.14/Changes000555001750001750 1057213647634102 15301 0ustar00jgamblejgamble000000000000Revision history for Math-Utils 1.14 10 Apr 2020 - Add the function softmax(). Currently in the :utility tag group, which may be too generic. We'll see what else gets added later and adjust the tagging then. - New functions uniform_scaling(), and uniform_01scaling(), contributed by Gene Boggs (GENE). - Typo found by Miguel Prz (NICEPERL) fixed. 1.13 30 Oct 2018 - Add function pl_translate(), by request. - Turn README into README.md. With MetaCPAN replacing CPAN, there is no reason to have a plain-text README anymore (MetaCPAN doesn't treat the file as special). - Add a CONTRIBUTING.md file, which is becoming a thing. - New test file for pl_translate(), and upgrade test files that for some reason were still using Test::Simple to Test::More. - Added an :all tag. Why not. 1.12 26 Jun 2018 - Typo found by Florian Schlichting fixed. - Add gcd() and lcm() functions. - New example scripts (a couple transferred over from Math::Polynomial::Solve) in the new eg/ directory. 1.11 11 Aug 2017 - Stupidly depended on Module::Start's boilerplate text for the license, which points to a differently worded license text from what I've got in the LICENSE file. Changed that. 1.10 10 May 2017 - Extended pl_evaluate() to allow lists of values for the X terms. Lists may be of values or of ARRAY refs. - Added tests in 16-evaluate.t for the list cases. 1.09 11 May 2016 - New function fsum(), using Kahan's summation algorithm. - Added tests in 17-derivative-eval.t to check for the linear polynomial and the constant-only polynomial. (They passed, but until now those cases hadn't been tested.) - Extend the documentation for pl_div(), emphasizing the need to remove leading zeros. 1.08 24 Feb 2016 - Inlined the comparison functions of generate_relational(). - Default tolerance was just under square root of (an) epsilon, changed to to just over. - Updated 01-compare.t to test edge cases. - Added a log2() function, because why not. 1.07 23 Nov 2015 - Search using grep.cpan.me indicated that floor() and ceil() functions weren't defined in general-purpose modules (and the modules they were in were pretty heavy-weight). Decided to add them to the module. - Repeated modulus of a number was worth making into utility function moduli(). 1.06 7 Oct 2015 - The if statements were laid out in generate_fltcmp in a way that could return a -1 (less than) when the two values were actually equal within tolerance. Changed this. - Renamed some test files so that the compare test comes first. 1.05 25 Sep 2015 - Bug in pl_derivative() for linear equation case. - Added test cases to cover it. 1.04 20 Sep 2015 - I had bumped the version number everywhere but in the module itself. This will probably complicate something, so fix this everywhere with a version 1.04. - Add a flipsign() function to the :utility list. - More documention clean-up. Mention Math::VecStat in the SEE ALSO. 1.03 18 Sep 2015 - Put :fortran tagged functions copysign() and log10() in the :utility tagging. The :fortran tag sticks around though. - New function pl_dxevaluate() for returning the y, dy, d2y values of the polynomial at x. - New test files for pl_evaluate() and pl_dxevaluate(). 1.02 15 Sep 2015 - Documentation error in pl_div() (mis-named variables in the example). - Extended the SEE ALSO paragraph. - Very minor code clean-up in pl_antiderivative(). 1.01 5 Sep 2015 - I had left test file 15-objcoeff.t off the MANIFEST list. Oops. - Embarrassing number of grammatical and spelling errors fixed. - Clarified a couple of examples, and extended the pl_antiderivative() documentation with respect to the constant term. - Version bump; up to CPAN. 1.00 3 Sep 2015 - Added the coefficient list functions for addition, subtraction, division, multiplication, derivative, antiderivative, and evaluation (via Horner's method) of polynomials without actually creating a polynomial object. - Added the tests for the above operations. 0.02 30 Aug 2015 - CPAN testers caught a 5.10ism in the module, which is listed as okay for version 5.8. Decided to bump the minimum version requirement to 5.10.1. - Documentation was sketchy, so added more descriptive text and examples. - Version bump; up to CPAN. 0.01 18 Aug 2015 - Collection of utility functions for Math modules, starting with the functions of Math-Fortran as a base. Math-Utils-1.14/LICENSE000444001750001750 4375413647634102 15020 0ustar00jgamblejgamble000000000000This software is copyright (c) 2020 by John M. Gamble . This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2020 by John M. Gamble . This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy 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 1, 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Artistic License 1.0 --- This software is Copyright (c) 2020 by John M. Gamble . This is free software, licensed under: The Artistic License 1.0 The Artistic License Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: - "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. - "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder. - "Copyright Holder" is whoever is named in the copyright or copyrights for the package. - "You" is you, if you're thinking about copying or distributing this Package. - "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) - "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as ftp.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End Math-Utils-1.14/MANIFEST000555001750001750 102413647634102 15107 0ustar00jgamblejgamble000000000000Build.PL Changes lib/Math/Utils.pm Makefile.PL MANIFEST This list of files README.md CONTRIBUTING.md eg/derivative.pl eg/division.pl eg/evaluate.pl eg/finitedif.pl eg/multiply.pl t/00-load.t t/01-compare.t t/02-signs.t t/03-logarithm.t t/04-fsum.t t/05-intfns.t t/06-moduli.t t/07-gcdlcm.t t/08-softmax.t t/09-scale.t t/10-add.t t/11-subtract.t t/12-multiply.t t/13-divide.t t/14-derivative.t t/15-objcoeff.t t/16-evaluate.t t/17-derivative-eval.t t/18-translate.t t/30-finitedif.t t/manifest.t t/pod.t LICENSE META.yml META.json Math-Utils-1.14/META.json000444001750001750 240513647634102 15400 0ustar00jgamblejgamble000000000000{ "abstract" : "Useful mathematical functions not in Perl", "author" : [ "John M. Gamble " ], "dynamic_config" : 0, "generated_by" : "Module::Build version 0.4224", "keywords" : [ "math", "math-utils", "sign", "gcd", "logarithm", "scale", "softmax", "comparison", "polymonial" ], "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "Math-Utils", "prereqs" : { "build" : { "requires" : { "Test::More" : "0" } }, "configure" : { "requires" : { "Module::Build" : "0.4" } }, "runtime" : { "requires" : { "perl" : "v5.10.1" } } }, "provides" : { "Math::Utils" : { "file" : "lib/Math/Utils.pm", "version" : "1.14" } }, "release_status" : "stable", "resources" : { "license" : [ "http://dev.perl.org/licenses/" ], "repository" : { "url" : "git://github.com/jgamble/Math-Utils.git" } }, "version" : "1.14", "x_serialization_backend" : "JSON::PP version 4.00" } Math-Utils-1.14/META.yml000444001750001750 144413647634102 15232 0ustar00jgamblejgamble000000000000--- abstract: 'Useful mathematical functions not in Perl' author: - 'John M. Gamble ' build_requires: Test::More: '0' configure_requires: Module::Build: '0.4' dynamic_config: 0 generated_by: 'Module::Build version 0.4224, CPAN::Meta::Converter version 2.150010' keywords: - math - math-utils - sign - gcd - logarithm - scale - softmax - comparison - polymonial license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Math-Utils provides: Math::Utils: file: lib/Math/Utils.pm version: '1.14' requires: perl: v5.10.1 resources: license: http://dev.perl.org/licenses/ repository: git://github.com/jgamble/Math-Utils.git version: '1.14' x_serialization_backend: 'CPAN::Meta::YAML version 0.018' Math-Utils-1.14/Makefile.PL000444001750001750 53713647634102 15715 0ustar00jgamblejgamble000000000000# Note: this file was auto-generated by Module::Build::Compat version 0.4224 require 5.010001; use ExtUtils::MakeMaker; WriteMakefile ( 'NAME' => 'Math::Utils', 'VERSION_FROM' => 'lib/Math/Utils.pm', 'PREREQ_PM' => { 'Test::More' => 0 }, 'INSTALLDIRS' => 'site', 'EXE_FILES' => [], 'PL_FILES' => {} ) ; Math-Utils-1.14/README.md000555001750001750 73013647634102 15220 0ustar00jgamblejgamble000000000000# Math-Utils ## Version 1.14 Contains implementations of commonly used mathematical functions and operations that are not part of standard Perl. ## INSTALLATION To install this module, run the following commands: ```bash perl Build.PL ./Build ./Build test ./Build install ``` ## COPYRIGHT AND LICENSE Copyright (C) 2020 John M. Gamble. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. Math-Utils-1.14/eg000755001750001750 013647634102 14214 5ustar00jgamblejgamble000000000000Math-Utils-1.14/eg/derivative.pl000555001750001750 147113647634102 17056 0ustar00jgamblejgamble000000000000#!/bin/perl # # use Carp; use Math::Utils qw(:polynomial); use Math::Complex; use strict; use warnings; while (my $line = prompt("Polynomial: ")) { my @polynomial = split(/,? /, $line); last unless ($line); my $x = prompt("x-value: "); d1(\@polynomial, $x); d2(\@polynomial, $x); } exit(0); sub d1 { my($p_ref, $x) = @_; my($r, $d1, $d2) = pl_dxevaluate($p_ref, $x); print "Polynomial: $r, First derivative: $d1, Second derivative $d2\n\n"; } sub d2 { my($p_ref, $x) = @_; my @d1p = pl_derivative(@$p_ref); my @d2p = pl_derivative(@d1p); my $r = pl_evaluate($p_ref, $x); my $d1 = pl_evaluate(\@d1p, $x); my $d2 = pl_evaluate(\@d2p, $x); print "Polynomial: $r, First derivative: $d1, Second derivative $d2\n\n"; } sub prompt { my $pr = shift; print $pr; my $inp = <>; chomp $inp; return $inp; } Math-Utils-1.14/eg/division.pl000555001750001750 222713647634102 16540 0ustar00jgamblejgamble000000000000#!/bin/perl # # use Carp; use Math::Utils qw(:polynomial); use Math::Complex; use strict; use warnings; while (my $line = prompt("Numerator Polynomial: ")) { my @polynomial = split(/[, ] */, $line); $line = prompt("Divided by: "); last unless ($line); my @divisor = split(/,? /, $line); my($q, $r) = pl_div(\@polynomial, \@divisor); my @quotient = @$q; my @remainder = @$r; print "Quotient: ", rootprint(@quotient), "\n"; print "Remainder: ", rootprint(@remainder), "\n\n"; } exit(0); sub cartesian_format { my($fmt_re, $fmt_im, @numbers) = @_; my(@cfn, $n, $r, $i); $fmt_re ||= "%.15g"; # Provide a default real format $fmt_im ||= " + %.15gi"; # Provide a default im format foreach $n (@numbers) { $r = sprintf($fmt_re, Re($n)); if (Im($n) != 0) { $i = sprintf($fmt_im, Im($n)); } else { $r = sprintf($fmt_re, $n); $i = ""; } push @cfn, $r . $i; } return wantarray? @cfn: $cfn[0]; } sub rootprint { my @fmtlist; foreach (@_) { push @fmtlist, cartesian_format(undef, undef, $_); } return "[ " . join(", ", @fmtlist) . " ]"; } sub prompt { my $pr = shift; print $pr; my $inp = <>; chomp $inp; return $inp; } Math-Utils-1.14/eg/evaluate.pl000555001750001750 77313647634102 16506 0ustar00jgamblejgamble000000000000#!/bin/perl # # use Carp; use Math::Utils qw(:polynomial); use Math::Complex; use strict; use warnings; while (my $line = prompt("Polynomial: ")) { my @polynomial = split(/[, ] */, $line); $line = prompt("X values: "); last unless ($line); my(@xvals) = split(/,? /, $line); my(@yvals) = pl_evaluate(\@polynomial, \@xvals); for my $j (0 .. $#yvals) { print $xvals[$j], ", ", $yvals[$j], "\n"; } } exit(0); sub prompt { my $pr = shift; print $pr; my $inp = <>; chomp $inp; return $inp; } Math-Utils-1.14/eg/finitedif.pl000555001750001750 767713647634102 16673 0ustar00jgamblejgamble000000000000#!/usr/bin/env perl use Math::Utils qw(:polynomial :utility); use Getopt::Long; #use Smart::Comments qw(###); use strict; use warnings; my($triangle, $verbose, $helpme); my($power, $startfrom) = (-1, 0); my(@yvals); GetOptions("power=i" => \$power, "start=i" => \$startfrom, "triangle" => \$triangle, "verbose" => \$verbose, "help" => \$helpme, ); if ($power >= 0) { @yvals = (0, 1); for my $j (2 .. $power + 1) { push @yvals, ($yvals[$j - 1] + $j ** $power); } } else { @yvals = @ARGV; } help() if ($helpme or ! scalar @yvals); my @fc = diff_column(@yvals); print_diff_triangle(diff_triangle(@yvals)) if ($triangle); print "\nDifference column:\n", join(", ", @fc), "\n" if ($verbose); my($m, $p) = make_poly(@fc); print "Polynomial is: [", join(", ", @{$p}), "]/$m\n"; exit (0); sub help { print << 'EOH'; Simple finite difference calculation to find the polynomial that generates the sequence that you provide. The numbers that you provide are the Y values; the coresponding X values are 0, 1, 2, ... etc. The polynomial is printed in ascending form. The output of finitedif.pl 1 10 27 52, for example, will be [1, 5, 4]/1. Ths translates to the polynomial 4*x**2 + 5*x + 1, all over the divisor 1. useage: finitedif.pl 1 10 27 52 or finitedif.pl --startfrom=1 1 10 27 52 or finitedif.pl --power=2 The flag "startfrom" starts X from a value other than 0. The flag "power" creates a power sequence (1, 4, 9, ... for power=2, 1, 8, 27, 64, ... for power=3, and so on). There are flags to display internal calculations: finitedif.pl --verbose 1 10 27 52 finitedif.pl --triangle 1 10 27 52 The flag "verbose" prints out intermediate calculations in addition to the polynomial. The flag "triangle" prints out the difference triangle. EOH exit(0); } # # using the first column of the difference triangle, create the polynomial. # sub make_poly { my(@diffs) = @_; my($n) = $#diffs; # # Set up the 1, x, x(x-1), x(x-1)(x-2), ... etc. polynomial sequence. # my $p = [1]; my @seq = ($p); for my $k (0 .. $#diffs) { $seq[$k] = [ map($_ * $diffs[$k], @{$p}) ]; $p = pl_mult($p, [-($startfrom + $k), 1]); } if ($verbose) { my $idx = 0; print "\nThe polynomial sequences:\n"; for my $q (@seq) { printf("%2d: [%s] / %d!\n", $idx, join(", ", @{$q}), $idx); $idx++; } print "\n"; } # # Add the sequences together to get one polynomial. # my $m = 1; $p = [0]; for my $k (reverse 1 .. $#diffs) { my $sk = [map($_ * $m, @{ $seq[$k] })]; $p = pl_add($p, $sk); $m *= $k; } $p = pl_add($p, [$m * $diffs[0]]); if ($verbose) { print "Added together:\n"; print "[", join(", ", @{$p}), "]/$m\n\n"; } # # Now find common factor and divide by it. # my(@coefs) = grep($_ != 0, @{$p}); if (scalar @coefs) { my $d = gcd(@coefs, $m); $p = [map($_/$d, @{$p})]; $m /= $d; } if ($verbose) { print "After reducing the fraction:\n"; print "[", join(", ", @{$p}), "]/$m\n\n"; } return ($m, $p); } sub print_diff_triangle { my(@diffs) = @_; for my $j (0 .. $#diffs) { my(@v) = @{$diffs[$j]}; print join(" ", map(sprintf("%10d", $_), @v)), "\n"; } } sub diff_triangle { my(@numbers) = @_; my(@diffs) = ([@numbers]); my $n = $#numbers; # # Create a new row by subracting number j from number j+1. # for my $j (1 .. $n) { my @v; push @v, $numbers[$_] - $numbers[$_ - 1] for (1 .. $#numbers); # # If it's a row of zeros, we're done anyway. # last unless (scalar grep($_ != 0, @v)); push @diffs, [@v]; @numbers = @v; } return @diffs; } sub diff_column { my(@numbers) = @_; my(@diffcol) = ($numbers[0]); my $n = $#numbers; # # Create a new row by subracting number j from number j+1. # for my $j (1 .. $n) { my @v; push @v, $numbers[$_] - $numbers[$_ - 1] for (1 .. $#numbers); # # If it's a row of zeros, we're done anyway. # last unless (scalar grep($_ != 0, @v)); push @diffcol, $v[0]; @numbers = @v; } return @diffcol; } Math-Utils-1.14/eg/multiply.pl000555001750001750 210313647634102 16564 0ustar00jgamblejgamble000000000000#!/bin/perl # # use Carp; use Math::Utils qw(:polynomial); use Math::Complex; use strict; use warnings; while (my $line = prompt("First Polynomial: ")) { my @polynomial = split(/[, ] */, $line); $line = prompt("Multiplied by: "); last unless ($line); my @multiplier = split(/,? /, $line); my $m = pl_mult(\@polynomial, \@multiplier); my @mul = @$m; print "Result: ", rootprint(@mul), "\n\n"; } exit(0); sub cartesian_format { my($fmt_re, $fmt_im, @numbers) = @_; my(@cfn, $n, $r, $i); $fmt_re ||= "%.15g"; # Provide a default real format $fmt_im ||= " + %.15gi"; # Provide a default im format foreach $n (@numbers) { $r = sprintf($fmt_re, Re($n)); if (Im($n) != 0) { $i = sprintf($fmt_im, Im($n)); } else { $r = sprintf($fmt_re, $n); $i = ""; } push @cfn, $r . $i; } return wantarray? @cfn: $cfn[0]; } sub rootprint { my @fmtlist; foreach (@_) { push @fmtlist, cartesian_format(undef, undef, $_); } return "[ " . join(", ", @fmtlist) . " ]"; } sub prompt { my $pr = shift; print $pr; my $inp = <>; chomp $inp; return $inp; } Math-Utils-1.14/lib000755001750001750 013647634102 14367 5ustar00jgamblejgamble000000000000Math-Utils-1.14/lib/Math000755001750001750 013647634102 15260 5ustar00jgamblejgamble000000000000Math-Utils-1.14/lib/Math/Utils.pm000555001750001750 5666013647634102 17113 0ustar00jgamblejgamble000000000000package Math::Utils; use 5.010001; use strict; use warnings; use Carp; use Exporter; our @ISA = qw(Exporter); our %EXPORT_TAGS = ( compare => [ qw(generate_fltcmp generate_relational) ], fortran => [ qw(log10 copysign) ], utility => [ qw(log10 log2 copysign flipsign sign floor ceil fsum gcd hcf lcm moduli softmax uniform_scaling uniform_01scaling) ], polynomial => [ qw(pl_evaluate pl_dxevaluate pl_translate pl_add pl_sub pl_div pl_mult pl_derivative pl_antiderivative) ], ); our @EXPORT_OK = ( @{ $EXPORT_TAGS{compare} }, @{ $EXPORT_TAGS{utility} }, @{ $EXPORT_TAGS{polynomial} }, ); # # Add an :all tag automatically. # $EXPORT_TAGS{all} = [@EXPORT_OK]; our $VERSION = '1.14'; =head1 NAME Math::Utils - Useful mathematical functions not in Perl. =head1 SYNOPSIS use Math::Utils qw(:utility); # Useful functions # # Base 10 and base 2 logarithms. # $scale = log10($pagewidth); $bits = log2(1/$probability); # # Two uses of sign(). # $d = sign($z - $w); @ternaries = sign(@coefficients); # # Using copysign(), $dist will be doubled negative or # positive $offest, depending upon whether ($from - $to) # is positive or negative. # my $dist = copysign(2 * $offset, $from - $to); # # Change increment direction if goal is negative. # $incr = flipsign($incr, $goal); # # floor() and ceil() functions. # $point = floor($goal); $limit = ceil($goal); # # gcd() and lcm() functions. # $divisor = gcd(@multipliers); $numerator = lcm(@multipliers); # # Safer summation. # $tot = fsum(@inputs); # # The remainders of n after successive divisions of b, or # remainders after a set of divisions. # @rems = moduli($n, $b); or use Math::Utils qw(:compare); # Make comparison functions with tolerance. # # Floating point comparison function. # my $fltcmp = generate_fltmcp(1.0e-7); if (&$fltcmp($x0, $x1) < 0) { add_left($data); } else { add_right($data); } # # Or we can create single-operation comparison functions. # # Here we are only interested in the greater than and less than # comparison functions. # my(undef, undef, $approx_gt, undef, $approx_lt) = generate_relational(1.5e-5); or use Math::Utils qw(:polynomial); # Basic polynomial ops # # Coefficient lists run from 0th degree upward, left to right. # my @c1 = (1, 3, 5, 7, 11, 13, 17, 19); my @c2 = (1, 3, 1, 7); my @c3 = (1, -1, 1) my $c_ref = pl_mult(\@c1, \@c2); $c_ref = pl_add($c_ref, \@c3); =head1 EXPORT All functions can be exported by name, or by using the tag that they're grouped under. =cut =head2 utility tag Useful, general-purpose functions, including those that originated in FORTRAN and were implemented in Perl in the module L, by J. A. R. Williams. There is a name change -- copysign() was known as sign() in Math::Fortran. =head3 log10() $xlog10 = log10($x); @xlog10 = log10(@x); Return the log base ten of the argument. A list form of the function is also provided. =cut sub log10 { my $log10 = log(10); return wantarray? map(log($_)/$log10, @_): log($_[0])/$log10; } =head3 log2() $xlog2 = log2($x); @xlog2 = log2(@x); Return the log base two of the argument. A list form of the function is also provided. =cut sub log2 { my $log2 = log(2); return wantarray? map(log($_)/$log2, @_): log($_[0])/$log2; } =head3 sign() $s = sign($x); @valsigns = sign(@values); Returns -1 if the argument is negative, 0 if the argument is zero, and 1 if the argument is positive. In list form it applies the same operation to each member of the list. =cut sub sign { return wantarray? map{($_ < 0)? -1: (($_ > 0)? 1: 0)} @_: ($_[0] < 0)? -1: (($_[0] > 0)? 1: 0); } =head3 copysign() $ms = copysign($m, $n); $s = copysign($x); Take the sign of the second argument and apply it to the first. Zero is considered part of the positive signs. copysign(-5, 0); # Returns 5. copysign(-5, 7); # Returns 5. copysign(-5, -7); # Returns -5. copysign(5, -7); # Returns -5. If there is only one argument, return -1 if the argument is negative, otherwise return 1. For example, copysign(1, -4) and copysign(-4) both return -1. =cut sub copysign { return ($_[1] < 0)? -abs($_[0]): abs($_[0]) if (@_ == 2); return ($_[0] < 0)? -1: 1; } =head3 flipsign() $ms = flipsign($m, $n); Multiply the signs of the arguments and apply it to the first. As with copysign(), zero is considered part of the positive signs. Effectively this means change the sign of the first argument if the second argument is negative. flipsign(-5, 0); # Returns -5. flipsign(-5, 7); # Returns -5. flipsign(-5, -7); # Returns 5. flipsign(5, -7); # Returns -5. If for some reason flipsign() is called with a single argument, that argument is returned unchanged. =cut sub flipsign { return -$_[0] if (@_ == 2 and $_[1] < 0); return $_[0]; } =head3 floor() $b = floor($a/2); @ilist = floor(@numbers); Returns the greatest integer less than or equal to its argument. A list form of the function also exists. floor(1.5, 1.87, 1); # Returns (1, 1, 1) floor(-1.5, -1.87, -1); # Returns (-2, -2, -1) =cut sub floor { return wantarray? map(($_ < 0 and int($_) != $_)? int($_ - 1): int($_), @_): ($_[0] < 0 and int($_[0]) != $_[0])? int($_[0] - 1): int($_[0]); } =head3 ceil() $b = ceil($a/2); @ilist = ceil(@numbers); Returns the lowest integer greater than or equal to its argument. A list form of the function also exists. ceil(1.5, 1.87, 1); # Returns (2, 2, 1) ceil(-1.5, -1.87, -1); # Returns (-1, -1, -1) =cut sub ceil { return wantarray? map(($_ > 0 and int($_) != $_)? int($_ + 1): int($_), @_): ($_[0] > 0 and int($_[0]) != $_[0])? int($_[0] + 1): int($_[0]); } =head3 fsum() Return a sum of the values in the list, done in a manner to avoid rounding and cancellation errors. Currently this is done via L. =cut sub fsum { my($sum, $c) = (0, 0); for my $v (@_) { my $y = $v - $c; my $t = $sum + $y; # # If we lost low-order bits of $y (usually because # $sum is much larger than $y), save them in $c # for the next loop iteration. # $c = ($t - $sum) - $y; $sum = $t; } return $sum; } =head3 softmax() Return a list of values as probabilities. The function takes the list, and creates a new list by raising I to each value. The function then returns each value divided by the sum of the list. Each value in the new list is now a set of probabilities that sum to 1.0. The summation is performed using I above. See L at Wikipedia. =cut sub softmax { my @nlist = @_; # # There's a nice trick where you find the maximum value in # the list, and subtract it from every number in the list. # This renders everything zero or negative, which makes # exponentation safe from overflow, but doesn't affect # the end result. # # If we weren't using this trick, then we'd start with # the 'my @explist' line, feeding it '@_' instead. # my $listmax = $nlist[0]; for (@nlist[1 .. $#nlist]) { $listmax = $_ if ($_ > $listmax); } @nlist = map{$_ - $listmax} @nlist if ($listmax > 0); my @explist = map{exp($_)} @nlist; my $sum = fsum(@explist); return map{$_/$sum} @explist; } =head3 uniform_scaling =head3 uniform_01scaling Uniformly, or linearly, scale a number either from one range to another range (C), or to a default range of [0 .. 1] (C). @v = uniform_scaling(\@original_range, \@new_range, @oldvalues); For example, these two lines are equivalent, and both return 0: $y = uniform_scaling([50, 100], [0, 1], 50); $y = uniform_01scaling([50, 100], 50); They may also be called with a list or array of numbers: @cm_measures = uniform_scaling([0, 10000], [0, 25400], @in_measures); @melt_centigrade = uniform_scaling([0, 2000], [-273.15, 1726.85], \@melting_points); A number that is outside the original bounds will be proportionally changed to be outside of the new bounds, but then again having a number outside the original bounds is probably an error that should be checked before calling this function. L =cut sub uniform_scaling { my @fromrange = @{$_[0]}; my @torange = @{$_[1]}; # # The remaining parameters are the numbers to rescale. # # It could happen. Someone might type \$x instead of $x. # my @xvalues = map{(ref $_ eq "ARRAY")? @$_: ((ref $_ eq "SCALAR")? $$_: $_)} @_[2 .. $#_]; return map{($_ - $fromrange[0])/($fromrange[1] - $fromrange[0]) * ($torange[1] - $torange[0]) + $torange[0]} @xvalues; } sub uniform_01scaling { my @fromrange = @{$_[0]}; # # The remaining parameters are the numbers to rescale. # # It could happen. Someone might type \$x instead of $x. # my @xvalues = map{(ref $_ eq "ARRAY")? @$_: ((ref $_ eq "SCALAR")? $$_: $_)} @_[1 .. $#_]; return map{($_ - $fromrange[0]) / ($fromrange[1] - $fromrange[0])} @xvalues; } =head3 gcd =head3 hcf Return the greatest common divisor (also known as the highest common factor) of a list of integers. These are simply synomyms: $factor = gcd(@numbers); $factor = hcf(@numbers); =cut sub gcd { use integer; my($x, $y, $r); # # It could happen. Someone might type \$x instead of $x. # my @values = map{(ref $_ eq "ARRAY")? @$_: ((ref $_ eq "SCALAR")? $$_: $_)} grep {$_} @_; return 0 if (scalar @values == 0); $y = abs pop @values; $x = abs pop @values; while (1) { ($x, $y) = ($y, $x) if ($y < $x); $r = $y % $x; $y = $x; if ($r == 0) { return $x if (scalar @values == 0); $r = abs pop @values; } $x = $r; } return $y; } # #sub bgcd #{ # my($x, $y) = map(abs($_), @_); # # return $y if ($x == 0); # return $x if ($y == 0); # # my $lsbx = low_set_bit($x); # my $lsby = low_set_bit($y); # $x >>= $lsbx; # $y >>= $lsby; # # while ($x != $y) # { # ($x, $y) = ($y, $x) if ($x > $y); # # $y -= $x; # $y >>= low_set_bit($y); # } # return ($x << (($lsbx > $lsby)? $lsby: $lsbx)); #} *hcf = \&gcd; =head3 lcm Return the least common multiple of a list of integers. $factor = lcm(@values); =cut sub lcm { # # It could happen. Someone might type \$x instead of $x. # my @values = map{(ref $_ eq "ARRAY")? @$_: ((ref $_ eq "SCALAR")? $$_: $_)} @_; my $x = pop @values; for my $m (@values) { $x *= $m/gcd($m, $x); } return abs $x; } =head3 moduli() Return the moduli of an integer after repeated divisions. The remainders are returned in a list from left to right. @digits = moduli(1899, 10); # Returns (9, 9, 8, 1) @rems = moduli(29, 3); # Returns (2, 0, 0, 1) =cut sub moduli { my($n, $b) = (abs($_[0]), abs($_[1])); my @mlist; use integer; for (;;) { push @mlist, $n % $b; $n /= $b; return @mlist if ($n == 0); } return (); } =head2 compare tag Create comparison functions for floating point (non-integer) numbers. Since exact comparisons of floating point numbers tend to be iffy, the comparison functions use a tolerance chosen by you. You may then use those functions from then on confident that comparisons will be consistent. If you do not provide a tolerance, a default tolerance of 1.49012e-8 (approximately the square root of an Intel Pentium's L) will be used. =head3 generate_fltcmp() Returns a comparison function that will compare values using a tolerance that you supply. The generated function will return -1 if the first argument compares as less than the second, 0 if the two arguments compare as equal, and 1 if the first argument compares as greater than the second. my $fltcmp = generate_fltcmp(1.5e-7); my(@xpos) = grep {&$fltcmp($_, 0) == 1} @xvals; =cut my $default_tolerance = 1.49012e-8; sub generate_fltcmp { my $tol = $_[0] // $default_tolerance; return sub { my($x, $y) = @_; return 0 if (abs($x - $y) <= $tol); return -1 if ($x < $y); return 1; } } =head3 generate_relational() Returns a list of comparison functions that will compare values using a tolerance that you supply. The generated functions will be the equivalent of the equal, not equal, greater than, greater than or equal, less than, and less than or equal operators. my($eq, $ne, $gt, $ge, $lt, $le) = generate_relational(1.5e-7); my(@approx_5) = grep {&$eq($_, 5)} @xvals; Of course, if you were only interested in not equal, you could use: my(undef, $ne) = generate_relational(1.5e-7); my(@not_around5) = grep {&$ne($_, 5)} @xvals; =cut sub generate_relational { my $tol = $_[0] // $default_tolerance; # # In order: eq, ne, gt, ge, lt, le. # return ( sub {return (abs($_[0] - $_[1]) <= $tol)? 1: 0;}, # eq sub {return (abs($_[0] - $_[1]) > $tol)? 1: 0;}, # ne sub {return ((abs($_[0] - $_[1]) > $tol) and ($_[0] > $_[1]))? 1: 0;}, # gt sub {return ((abs($_[0] - $_[1]) <= $tol) or ($_[0] > $_[1]))? 1: 0;}, # ge sub {return ((abs($_[0] - $_[1]) > $tol) and ($_[0] < $_[1]))? 1: 0;}, # lt sub {return ((abs($_[0] - $_[1]) <= $tol) or ($_[0] < $_[1]))? 1: 0;} # le ); } =head2 polynomial tag Perform some polynomial operations on plain lists of coefficients. # # The coefficient lists are presumed to go from low order to high: # @coefficients = (1, 2, 4, 8); # 1 + 2x + 4x**2 + 8x**3 In all functions the coeffcient list is passed by reference to the function, and the functions that return coefficients all return references to a coefficient list. B This caveat is particularly important to note in the case of C. Although these functions are convenient for simple polynomial operations, for more advanced polynonial operations L is recommended. =head3 pl_evaluate() Returns either a y-value for a corresponding x-value, or a list of y-values on the polynomial for a corresponding list of x-values, using Horner's method. $y = pl_evaluate(\@coefficients, $x); @yvalues = pl_evaluate(\@coefficients, @xvalues); @ctemperatures = pl_evaluate([-160/9, 5/9], @ftemperatures); The list of X values may also include X array references: @yvalues = pl_evaluate(\@coefficients, @xvalues, \@primes, $x, [-1, -10, -100]); =cut sub pl_evaluate { my @coefficients = @{$_[0]}; # # It could happen. Someone might type \$x instead of $x. # my @xvalues = map{(ref $_ eq "ARRAY")? @$_: ((ref $_ eq "SCALAR")? $$_: $_)} @_[1 .. $#_]; # # Move the leading coefficient off the polynomial list # and use it as our starting value(s). # my @results = (pop @coefficients) x scalar @xvalues; for my $c (reverse @coefficients) { for my $j (0..$#xvalues) { $results[$j] = $results[$j] * $xvalues[$j] + $c; } } return wantarray? @results: $results[0]; } =head3 pl_dxevaluate() ($y, $dy, $ddy) = pl_dxevaluate(\@coefficients, $x); Returns p(x), p'(x), and p"(x) of the polynomial for an x-value, using Horner's method. Note that unlike C above, the function can only use one x-value. If the polynomial is a linear equation, the second derivative value will be zero. Similarly, if the polynomial is a simple constant, the first derivative value will be zero. =cut sub pl_dxevaluate { my($coef_ref, $x) = @_; my(@coefficients) = @$coef_ref; my $n = $#coefficients; my $val = pop @coefficients; my $d1val = $val * $n; my $d2val = 0; # # Special case for the linear eq'n (the y = constant eq'n # takes care of itself). # if ($n == 1) { $val = $val * $x + $coefficients[0]; } elsif ($n >= 2) { my $lastn = --$n; $d2val = $d1val * $n; # # Loop through the coefficients, except for # the linear and constant terms. # for my $c (reverse @coefficients[2..$lastn]) { $val = $val * $x + $c; $d1val = $d1val * $x + ($c *= $n--); $d2val = $d2val * $x + ($c * $n); } # # Handle the last two coefficients. # $d1val = $d1val * $x + $coefficients[1]; $val = ($val * $x + $coefficients[1]) * $x + $coefficients[0]; } return ($val, $d1val, $d2val); } =head3 pl_translate() $x = [8, 3, 1]; $y = [3, 1]; # # Translating C by C returns [26, 9, 1] # $z = pl_translate($x, $y); Returns a polynomial transformed by substituting a polynomial variable with another polynomial. For example, a simple linear translation by 1 to the polynomial C would be accomplished by setting x = (y - 1); resulting in C. $x = [4, 4, 1, 1]; $y = [-1, 1]; $z = pl_translate($x, $y); # Becomes [0, 5, -2, 1] =cut sub pl_translate { my($x, $y) = @_; my @x_arr = @$x; my @z = pop @x_arr; for my $c (reverse @x_arr) { @z = @{ pl_mult(\@z, $y) }; $z[0] += $c; } return [@z]; } =head3 pl_add() $polyn_ref = pl_add(\@m, \@n); Add two lists of numbers as though they were polynomial coefficients. =cut sub pl_add { my(@av) = @{$_[0]}; my(@bv) = @{$_[1]}; my $ldiff = scalar @av - scalar @bv; my @result = ($ldiff < 0)? splice(@bv, scalar @bv + $ldiff, -$ldiff): splice(@av, scalar @av - $ldiff, $ldiff); unshift @result, map($av[$_] + $bv[$_], 0.. $#av); return \@result; } =head3 pl_sub() $polyn_ref = pl_sub(\@m, \@n); Subtract the second list of numbers from the first as though they were polynomial coefficients. =cut sub pl_sub { my(@av) = @{$_[0]}; my(@bv) = @{$_[1]}; my $ldiff = scalar @av - scalar @bv; my @result = ($ldiff < 0)? map {-$_} splice(@bv, scalar @bv + $ldiff, -$ldiff): splice(@av, scalar @av - $ldiff, $ldiff); unshift @result, map($av[$_] - $bv[$_], 0.. $#av); return \@result; } =head3 pl_div() ($q_ref, $r_ref) = pl_div(\@numerator, \@divisor); Synthetic division for polynomials. Divides the first list of coefficients by the second list. Returns references to the quotient and the remainder. Remember to check for leading zeros (which are rightmost in the list) in the returned values. For example, my @n = (4, 12, 9, 3); my @d = (1, 3, 3, 1); my($q_ref, $r_ref) = pl_div(\@n, \@d); After division you will have returned C<(3)> as the quotient, and C<(1, 3, 0)> as the remainder. In general, you will want to remove the leading zero, or for that matter values within epsilon of zero, in the remainder. my($q_ref, $r_ref) = pl_div($f1, $f2); # # Remove any leading zeros (i.e., numbers smaller in # magnitude than machine epsilon) in the remainder. # my @remd = @{$r_ref}; pop @remd while (@remd and abs($remd[$#remd]) < $epsilon); $f1 = $f2; $f2 = [@remd]; If C<$f1> and C<$f2> were to go through that bit of code again, not removing the leading zeros would lead to a divide-by-zero error. If either list of coefficients is empty, pl_div() returns undefs for both quotient and remainder. =cut sub pl_div { my @numerator = @{$_[0]}; my @divisor = @{$_[1]}; my @quotient; my $n_degree = $#numerator; my $d_degree = $#divisor; # # Sanity checks: a numerator less than the divisor # is automatically the remainder; and return a pair # of undefs if either set of coefficients are # empty lists. # return ([0], \@numerator) if ($n_degree < $d_degree); return (undef, undef) if ($d_degree < 0 or $n_degree < 0); my $lead_coefficient = $divisor[$#divisor]; # # Perform the synthetic division. The remainder will # be what's left in the numerator. # (4, 13, 4, -9, 6) / (1, 2) = (4, 5, -6, 3) # @quotient = reverse map { # # Get the next term for the quotient. We pop # off the lead numerator term, which would become # zero due to subtraction anyway. # my $q = (pop @numerator)/$lead_coefficient; for my $k (0..$d_degree - 1) { $numerator[$#numerator - $k] -= $q * $divisor[$d_degree - $k - 1]; } $q; } reverse (0 .. $n_degree - $d_degree); return (\@quotient, \@numerator); } =head3 pl_mult() $m_ref = pl_mult(\@coefficients1, \@coefficients2); Returns the reference to the product of the two multiplicands. =cut sub pl_mult { my($av, $bv) = @_; my $a_degree = $#{$av}; my $b_degree = $#{$bv}; # # Rather than multiplying left to right for each element, # sum to each degree of the resulting polynomial (the list # after the map block). Still an O(n**2) operation, but # we don't need separate storage variables. # return [ map { my $a_idx = ($a_degree > $_)? $_: $a_degree; my $b_to = ($b_degree > $_)? $_: $b_degree; my $b_from = $_ - $a_idx; my $c = $av->[$a_idx] * $bv->[$b_from]; for my $b_idx ($b_from+1 .. $b_to) { $c += $av->[--$a_idx] * $bv->[$b_idx]; } $c; } (0 .. $a_degree + $b_degree) ]; } =head3 pl_derivative() $poly_ref = pl_derivative(\@coefficients); Returns the derivative of a polynomial. =cut sub pl_derivative { my @coefficients = @{$_[0]}; my $degree = $#coefficients; return [] if ($degree < 1); $coefficients[$_] *= $_ for (2..$degree); shift @coefficients; return \@coefficients; } =head3 pl_antiderivative() $poly_ref = pl_antiderivative(\@coefficients); Returns the antiderivative of a polynomial. The constant value is always set to zero and will need to be changed by the caller if a different constant is needed. my @coefficients = (1, 2, -3, 2); my $integral = pl_antiderivative(\@coefficients); # # Integral needs to be 0 at x = 1. # my @coeff1 = @{$integral}; $coeff1[0] = - pl_evaluate($integral, 1); =cut sub pl_antiderivative { my @coefficients = @{$_[0]}; my $degree = scalar @coefficients; # # Sanity check if its an empty list. # return [0] if ($degree < 1); $coefficients[$_ - 1] /= $_ for (2..$degree); unshift @coefficients, 0; return \@coefficients; } =head1 AUTHOR John M. Gamble, C<< >> =head1 SEE ALSO L for a complete set of polynomial operations, with the added convenience that objects bring. Among its other functions, L has the mathematically useful functions max(), min(), product(), sum(), and sum0(). L has the function minmax(). L has gcd() and lcm() functions, as well as vecsum(), vecprod(), vecmin(), and vecmax(), which are like the L functions but which can force integer use, and when appropriate use L. L Likewise has min(), max(), sum() (which can take as arguments array references as well as arrays), plus maxabs(), minabs(), sumbyelement(), convolute(), and other functions. =head1 BUGS Please report any bugs or feature requests to C, or through the web interface at L. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes. =head1 SUPPORT This module is on Github at L. You can also look for information at: =over 4 =item * RT: CPAN's request tracker (report bugs here) L =item * MetaCPAN L =back =head1 ACKNOWLEDGEMENTS To J. A. R. Williams who got the ball rolling with L. =head1 LICENSE AND COPYRIGHT Copyright (c) 2017 John M. Gamble. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself. =cut 1; # End of Math::Utils Math-Utils-1.14/t000755001750001750 013647634102 14064 5ustar00jgamblejgamble000000000000Math-Utils-1.14/t/00-load.t000555001750001750 34613647634102 15530 0ustar00jgamblejgamble000000000000#!perl -T use 5.010001; use strict; use warnings FATAL => 'all'; use Test::More; plan tests => 1; BEGIN { use_ok( 'Math::Utils' ) || print "Bail out!\n"; } diag( "Testing Math::Utils $Math::Utils::VERSION, Perl $], $^X" ); Math-Utils-1.14/t/01-compare.t000555001750001750 354313647634102 16262 0ustar00jgamblejgamble000000000000#!perl -T use 5.010001; use strict; use warnings; use Test::More tests => 13; use Math::Utils qw(:compare); my $fltcmp = generate_fltcmp(); # Use default tolerance. ok(&$fltcmp(sqrt(2), 1.414213562) == 0, "sqrt(2) check."); # # In order, the comparison ops are eq, ne, gt, ge, lt, le. # For simple testing, use a big tolerance of one half. # my(@relfs) = generate_relational(0.5); # # x positive, y positive. # my $x = 1; my $y = 1.25; my $pass = join("", map{&$_($x, $y)} @relfs); ok($pass eq "100101", "$x op $y check returns $pass."); $y = 1.5; $pass = join("", map{&$_($x, $y)} @relfs); ok($pass eq "100101", "$x op $y check returns $pass."); $y = 1.75; $pass = join("", map{&$_($x, $y)} @relfs); ok($pass eq "010011", "$x op $y check returns $pass."); # # x negative, y negative. # $x = -1; $y = -1.25; $pass = join("", map{&$_($x, $y)} @relfs); ok($pass eq "100101", "$x op $y check returns $pass."); $y = -1.5; $pass = join("", map{&$_($x, $y)} @relfs); ok($pass eq "100101", "$x op $y check returns $pass."); $y = -1.75; $pass = join("", map{&$_($x, $y)} @relfs); ok($pass eq "011100", "$x op $y check returns $pass."); # # x positive, y negative. # $x = 1; $y = -1.25; $pass = join("", map{&$_($x, $y)} @relfs); ok($pass eq "011100", "$x op $y check returns $pass."); $y = -1.5; $pass = join("", map{&$_($x, $y)} @relfs); ok($pass eq "011100", "$x op $y check returns $pass."); $y = -1.75; $pass = join("", map{&$_($x, $y)} @relfs); ok($pass eq "011100", "$x op $y check returns $pass."); # # x negative, y positive. # $x = -1; $y = 1.25; $pass = join("", map{&$_($x, $y)} @relfs); ok($pass eq "010011", "$x op $y check returns $pass."); $y = 1.5; $pass = join("", map{&$_($x, $y)} @relfs); ok($pass eq "010011", "$x op $y check returns $pass."); $y = 1.75; $pass = join("", map{&$_($x, $y)} @relfs); ok($pass eq "010011", "$x op $y check returns $pass."); Math-Utils-1.14/t/02-signs.t000555001750001750 177713647634102 15767 0ustar00jgamblejgamble000000000000#!perl use 5.010001; use strict; use warnings; use Test::More tests => 12; use Math::Utils qw(sign copysign); my($sn, $snjoin); $sn = sign(-12); ok($sn == -1, "sign(-12) returned $sn"); $sn = sign(12); ok($sn == 1, "sign(12) returned $sn"); $sn = sign(0); ok($sn == 0, "sign(0) returned $sn"); $snjoin = join("", sign(-12, 5)); ok($snjoin eq "-11", "sign(-12, 5) returned $snjoin"); $snjoin = join("", sign(12, -5)); ok($snjoin eq "1-1", "sign(12, -5) returned $snjoin"); $snjoin = join("", sign(-12, 0, 2, 9, 0.5, -0.5)); ok($snjoin eq "-10111-1", "sign(-12, 0, 2, 9, 0.5, -0.5) returned $snjoin"); $sn = copysign(-12); ok($sn == -1, "copysign(-12) returned $sn"); $sn = copysign(12); ok($sn == 1, "copysign(12) returned $sn"); $sn = copysign(0); ok($sn == 1, "copysign(0) returned $sn"); $sn = copysign(-12, 5); ok($sn == 12, "copysign(-12, 5) returned $sn"); $sn = copysign(12, -5); ok($sn == -12, "copysign(12, -5) returned $sn"); $sn = copysign(-12, 0); ok($sn == 12, "copysign(-12, 0) returned $sn"); Math-Utils-1.14/t/03-logarithm.t000555001750001750 101213647634102 16611 0ustar00jgamblejgamble000000000000#!perl -T use 5.010001; use strict; use warnings; use Test::More tests => 12; use Math::Utils qw(:compare log10 log2); my($eq, $ne) = generate_relational(1.5e-7); my @logs = ("no", 0, 0.301029995, 0.4771212547, 0.602059991, 0.698970004, 0.7781512503, ); for my $x (1 .. 6) { my $y = log10($x); ok(&$eq($y, $logs[$x]), "log10($x) returned $y"); } my @lgs = ("no", 0, 1.0, 1.584962501, 2.0, 2.321928095, 2.584962501, ); for my $x (1 .. 6) { my $y = log2($x); ok(&$eq($y, $lgs[$x]), "log2($x) returned $y"); } Math-Utils-1.14/t/04-fsum.t000555001750001750 106113647634102 15602 0ustar00jgamblejgamble000000000000#!perl use 5.010001; use strict; use warnings; use Test::More tests => 3; use Math::Utils qw(:utility :compare); my $fltcmp = generate_fltcmp(1e-5); my $sum; $sum = fsum(0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1); #diag($sum); ok(&$fltcmp($sum, 1) == 0, "fsum() of 10 0.1s"); $sum = fsum(10000, 3.14159, 2.71828); #diag($sum); ok(&$fltcmp($sum, 10005.85987) == 0, "fsum() of 10000, 3.14159, 2.71828"); $sum = fsum(10000, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1); #diag($sum); ok(&$fltcmp($sum, 10001) == 0, "fsum() of 1000 plus 10 0.1s"); Math-Utils-1.14/t/05-intfns.t000555001750001750 134013647634102 16132 0ustar00jgamblejgamble000000000000#!perl -T use 5.010001; use strict; use warnings; use Test::More tests => 8; use Math::Utils qw(:utility); my @f; my $fstr; ok(floor(1.5) == 1, "floor(1.5)"); ok(floor(-1.5) == -2, "floor(-1.5)"); ok(ceil(1.5) == 2, "ceil(1.5)"); ok(ceil(-1.5) == -1, "ceil(-1.5)"); @f = floor(1.5, 1.87, 1); $fstr = join(", ", @f); ok($fstr eq "1, 1, 1", "floor(1.5, 1.87, 1) returned $fstr"); @f = floor(-1.5, -1.87, -1); $fstr = join(", ", @f); ok($fstr eq "-2, -2, -1", "floor(-1.5, -1.87, -1) returned $fstr"); @f = ceil(1.5, 1.87, 1); $fstr = join(", ", @f); ok($fstr eq "2, 2, 1", "ceil(1.5, 1.87, 1) returned $fstr"); @f = ceil(-1.5, -1.87, -1); $fstr = join(", ", @f); ok($fstr eq "-1, -1, -1", "ceil(-1.5, -1.87, -1) returned $fstr"); Math-Utils-1.14/t/06-moduli.t000555001750001750 112113647634102 16120 0ustar00jgamblejgamble000000000000#!perl -T use 5.010001; use strict; use warnings; use Test::More tests => 2; use Math::Utils qw(:utility); my @rem; my $rstr; @rem = moduli(29, 3); $rstr = join("", @rem); ok($rstr eq "2001", "moduli(29, 3) returned $rstr"); @rem = moduli(4095, 2); $rstr = join("", @rem); ok($rstr eq "111111111111", "moduli(4095, 2) returned $rstr"); #@rem = moduli(29, [4, 9]); #$rstr = join("", @rem); #ok($rstr eq "17", "moduli(29, [4, 9]) returned $rstr"); #@rem = moduli(803151, [4, 5, 8, 9]); #$rstr = join(", ", @rem); #ok($rstr eq "3, 2, 5, 6", "moduli(803151, [4, 5, 8, 9]) returned $rstr"); Math-Utils-1.14/t/07-gcdlcm.t000555001750001750 70513647634102 16050 0ustar00jgamblejgamble000000000000#!perl -T use 5.010001; use strict; use warnings; use Test::More tests => 4; use Math::Utils qw(:utility); my $factor; $factor = gcd(29, 3); ok($factor == 1, "gcd(29, 3) returned $factor"); $factor = gcd(4095, 45); ok($factor == 45, "gcd(4095, 45) returned $factor"); $factor = hcf(72, [12, 9]); ok($factor == 3, "hcf(72, [12, 9]) returned $factor"); $factor = hcf(803151, 36, 18, 9); ok($factor == 9, "hcf(803151, 36, 18, 9) returned $factor"); Math-Utils-1.14/t/08-softmax.t000444001750001750 113613647634102 16315 0ustar00jgamblejgamble000000000000# Before `make install' is performed this script should be runnable with # `make test'. After `make install' it should work as `perl 20-softmax.t' use 5.010001; use Test::More tests => 2; use Math::Utils qw(:utility :compare); use strict; use warnings; my $fltcmp = generate_fltcmp(1e-7); my @trials = ( [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [0, 1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1 ], ); for my $t (@trials) { my @probs = softmax(@$t); ok( (&$fltcmp(fsum(@probs), 1.0) == 0), " softmax(" . join(", ", @$t) . ") returns\n" . " [" . join(", ", @probs) . "], did not sum to 1.0\n" ); } Math-Utils-1.14/t/09-scale.t000555001750001750 317113647634102 15730 0ustar00jgamblejgamble000000000000# Before `make install' is performed this script should be runnable with # `make test'. After `make install' it should work as `perl 19-scale.t' use 5.010001; use Test::More tests => 14; use Math::Utils qw(:utility :compare); use strict; use warnings; my $fltcmp = generate_fltcmp(1e-7); # # Cut a range by half (just random examples); # Kelvin to Centigrade (melting points of gold, silver, and copper); # and arithmetic RGB to 8-bit RGB (before rounding them to integers). # my @trials = ( [ [0, 100], [0, 50], [10, 25, 37, 49, 50], [5, 12.5, 18.5, 24.5, 25] ], [ [0, 2000], [-273.15, 1726.85], [1337.33, 1234.93, 1357.77], [1064.18, 961.78, 1084.62] ], [ [0, 1], [0, 256], [0.93, 0.42, 0.33], [238.08, 107.52, 84.48] ], ); for my $t (@trials) { my @case = @$t; my @scale0 = @{$case[0]}; my @scale1 = @{$case[1]}; my @value0 = @{$case[2]}; my @value1 = @{$case[3]}; my @scale_v = uniform_scaling(\@scale0, \@scale1, \@value0); for my $idx (0 .. $#scale_v) { ok( (&$fltcmp($scale_v[$idx], $value1[$idx]) == 0), " " . $value0[$idx] . " to " . $value1[$idx] . " returned" . $scale_v[$idx] . "\n" ); } } # # 8-bit RGB to arithmetic RGB (before rounding to two decimal places). # my @trials01 = ( [ [0, 256], [238, 108, 84], [0.9296875, 0.421875, 0.328125] ], ); for my $t (@trials01) { my @case = @$t; my @scale0 = @{$case[0]}; my @value0 = @{$case[1]}; my @value1 = @{$case[2]}; my @scale_v = uniform_01scaling(\@scale0, \@value0); for my $idx (0 .. $#scale_v) { ok( (&$fltcmp($scale_v[$idx], $value1[$idx]) == 0), " " . $value0[$idx] . " to " . $value1[$idx] . " returned" . $scale_v[$idx] . "\n" ); } } 1; Math-Utils-1.14/t/10-add.t000555001750001750 242213647634102 15357 0ustar00jgamblejgamble000000000000# Before `make install' is performed this script should be runnable with # `make test'. After `make install' it should work as `perl 10-add.t' use 5.010001; use Test::More tests => 3; use Math::Utils qw(:polynomial); use strict; use warnings; # # returns 0 (equal) or 1 (not equal). There's no -1 value, # unlike other cmp functions. # sub polycmp { my($p_ref1, $p_ref2) = @_; my @polynomial1 = @$p_ref1; my @polynomial2 = @$p_ref2; return 1 if (scalar @polynomial1 != scalar @polynomial2); foreach my $c1 (@polynomial1) { my $c2 = shift @polynomial2; return 1 if ($c1 != $c2); } return 0; } # # Groups of three: two to add and an answer. # Remember polynomial degree goes from left to right. # my @case0 = ( [ [90, -53, 7, -70, 49, -7, -20, 4], [9, -8, 4], [99, -61, 11, -70, 49, -7, -20, 4] ], [ [1, 4, 8, 4, 1], [1, 0, 0, 5, 34, 0, 0, 0, 9], [2, 4, 8, 9, 35, 0, 0, 0, 9], ], [ [4, 12, 9, 3], [1, 3, 3, 1], [5, 15, 12, 4] ] ); foreach my $cref (@case0) { my($n1_ref, $n2_ref, $r_ref) = @$cref; my($r) = pl_add($n1_ref, $n2_ref); my @n1 = @$n1_ref; my @n2 = @$n2_ref; my @ans = @$r; ok((polycmp($r_ref, $r) == 0), " [ " . join(", ", @n1) . " ] +" . " [ " . join(", ", @n2) . " ] returns\n" . " [ " . join(", ", @ans) . " ]\n" ); } 1; Math-Utils-1.14/t/11-subtract.t000555001750001750 242713647634102 16464 0ustar00jgamblejgamble000000000000# Before `make install' is performed this script should be runnable with # `make test'. After `make install' it should work as `perl 11-subtract.t' use 5.010001; use Test::More tests => 3; use Math::Utils qw(:polynomial); use strict; use warnings; # # returns 0 (equal) or 1 (not equal). There's no -1 value, # unlike other cmp functions. # sub polycmp { my($p_ref1, $p_ref2) = @_; my @polynomial1 = @$p_ref1; my @polynomial2 = @$p_ref2; return 1 if (scalar @polynomial1 != scalar @polynomial2); foreach my $c1 (@polynomial1) { my $c2 = shift @polynomial2; return 1 if ($c1 != $c2); } return 0; } # # Groups of three: two to add and an answer. # Remember polynomial degree goes from left to right. # my @case0 = ( [ [90, -53, 7, -70, 49, -7, -20, 4], [9, -8, 4], [81, -45, 3, -70, 49, -7, -20, 4] ], [ [1, 4, 8, 4, 1], [1, 0, 0, 5, 34, 0, 0, 0, 9], [0, 4, 8, -1, -33, 0, 0, 0, -9], ], [ [4, 12, 9, 3], [1, 3, 3, 1], [3, 9, 6, 2] ] ); foreach my $cref (@case0) { my($n1_ref, $n2_ref, $r_ref) = @$cref; my($r) = pl_sub($n1_ref, $n2_ref); my @n1 = @$n1_ref; my @n2 = @$n2_ref; my @ans = @$r; ok((polycmp($r_ref, $r) == 0), " [ " . join(", ", @n1) . " ] -" . " [ " . join(", ", @n2) . " ] returns\n" . " [ " . join(", ", @ans) . " ]\n" ); } 1; Math-Utils-1.14/t/12-multiply.t000555001750001750 230613647634102 16511 0ustar00jgamblejgamble000000000000# Before `make install' is performed this script should be runnable with # `make test'. After `make install' it should work as `perl 12-multiply.t' use 5.010001; use Test::More tests => 3; use Math::Utils qw(:polynomial); use strict; use warnings; # # returns 0 (equal) or 1 (not equal). There's no -1 value, unlike other cmp functions. # sub polycmp { my($p_ref1, $p_ref2) = @_; my @polynomial1 = @$p_ref1; my @polynomial2 = @$p_ref2; return 1 if (scalar @polynomial1 != scalar @polynomial2); foreach my $c1 (@polynomial1) { my $c2 = shift @polynomial2; return 1 if ($c1 != $c2); } return 0; } # # Groups of three: two multipliers and the answer. # my @case0 = ( [ [9, -8, 4], [10, 3, -1, -10, -3, 1], [90, -53, 7, -70, 49, -7, -20, 4], ], [ [1, 4, 8, 4, 1], [1, -4, 8, -4, 1], [1, 0, 0, 0, 34, 0, 0, 0, 1], ], [ [1, 3, 3, 1], [3], [3, 9, 9, 3], ] ); foreach my $cref (@case0) { my($n1_ref, $n2_ref, $m_ref) = @$cref; my($r) = pl_mult($n1_ref, $n2_ref); my @n1 = @$n1_ref; my @n2 = @$n2_ref; my @ans = @$r; ok((polycmp($m_ref, $r) == 0), " [ " . join(", ", @n1) . " ] *" . " [ " . join(", ", @n2) . " ] returns\n" . " [ " . join(", ", @ans) . " ]\n" ); } 1; Math-Utils-1.14/t/13-divide.t000555001750001750 307313647634102 16101 0ustar00jgamblejgamble000000000000# Before `make install' is performed this script should be runnable with # `make test'. After `make install' it should work as `perl 13-divide.t' use 5.010001; use Test::More tests => 5; use Math::Utils qw(:polynomial); use strict; use warnings; # # returns 0 (equal) or 1 (not equal). There's no -1 value, unlike other cmp functions. # sub polycmp { my($p_ref1, $p_ref2) = @_; my @polynomial1 = @$p_ref1; my @polynomial2 = @$p_ref2; return 1 if (scalar @polynomial1 != scalar @polynomial2); foreach my $c1 (@polynomial1) { my $c2 = shift @polynomial2; return 1 if ($c1 != $c2); } return 0; } # # Groups of four: numerator, divisor, quotient, remainder. # my @case0 = ( [ [90, -53, 7, -70, 49, -7, -20, 4], [9, -8, 4], [10, 3, -1, -10, -3, 1], [0, 0] ], [ [1, 0, 0, 0, 34, 0, 0, 0, 1], [1, 4, 8, 4, 1], [1, -4, 8, -4, 1], [0, 0, 0, 0] ], [ [1, 6, 15, 32, 58, 88, 116, 160, 165, 138, 133], [1, 3, 5, 7, 11, 13, 17, 19], [1, 3, 1, 7], [0, 0, 0, 0, 0, 0, 0] ], [ [4, 12, 9, 3], [1, 3, 3, 1], [3], [1, 3, 0] ], [ [4, 13, 4, -9, 6], [1, 2], [4, 5, -6, 3], [0] ] ); foreach my $cref (@case0) { my($p_ref, $d_ref, $q_ref, $r_ref) = @$cref; my($q, $r) = pl_div($p_ref, $d_ref); my @polynomial = @$p_ref; my @divisor = @$d_ref; my @quotient = @$q; my @remainder = @$r; ok((polycmp($q_ref, $q) == 0 and polycmp($r_ref, $r) == 0), " [ " . join(", ", @polynomial) . " ] /" . " [ " . join(", ", @divisor) . " ] returns\n" . " [ " . join(", ", @quotient) . " ] and" . " [ " . join(", ", @remainder) . " ].\n" ); } 1; Math-Utils-1.14/t/14-derivative.t000555001750001750 307613647634102 17003 0ustar00jgamblejgamble000000000000# Before `make install' is performed this script should be runnable with # `make test'. After `make install' it should work as `perl 14-derivative.t' use 5.010001; use Test::More tests => 16; use Math::Utils qw(:polynomial); use strict; use warnings; # # returns 0 (equal) or 1 (not equal). There's no -1 value, unlike other cmp functions. # sub polycmp { my($p_ref1, $p_ref2) = @_; my @polynomial1 = @$p_ref1; my @polynomial2 = @$p_ref2; return 1 if (scalar @polynomial1 != scalar @polynomial2); foreach my $c1 (@polynomial1) { my $c2 = shift @polynomial2; return 1 if ($c1 != $c2); } return 0; } # # Pairs of polynomnials and their derivatives. # my @case = ( [1], [], [3, 5], [5], [1, 24, 32], [24, 64], [289, 4, 3, 2, 1], [4, 6, 6, 4], [-1, -3, 0, 0, 0, 1], [-3, 0, 0, 0, 5], [90, -53, 7, -70, 49, -7, -20, 4], [-53, 14, -210, 196, -35, -120, 28], [1, 0, 0, 0, 34, 0, 0, 0, 1], [0, 0, 0, 136, 0, 0, 0, 8], [4, 12, 9, 3], [12, 18, 9], ); # # Peel off two items per loop. # while (@case) { my $p_ref = shift @case; my $d_ref = shift @case; my @polynomial = @$p_ref; my $constant = $polynomial[0]; my $derivative = pl_derivative(\@polynomial); ok((polycmp($d_ref, $derivative) == 0), " f() = [ " . join(", ", @polynomial) . " ]\n" . " f'() = [ " . join(", ", @{$derivative}) . " ].\n" ); my $antiderivative = pl_antiderivative($derivative); $antiderivative->[0] = $constant; ok((polycmp($p_ref, $antiderivative) == 0), " f() = [ " . join(", ", @{$derivative}) . " ]\n" . " integral f() = [ " . join(", ", @{$antiderivative}) . " ].\n" ); } 1; Math-Utils-1.14/t/15-objcoeff.t000555001750001750 325113647634102 16412 0ustar00jgamblejgamble000000000000# Before `make install' is performed this script should be runnable with # `make test'. After `make install' it should work as `perl 15-objcoeff.t' use 5.010001; use Test::More tests => 2; use Math::Utils qw(:polynomial); use Math::Complex; use Math::BigRat; use strict; use warnings; # # Test if the polynomial functions work with coefficients that are objects. # # # returns 0 (equal) or 1 (not equal). There's no -1 value, unlike other # cmp functions. # sub polycmp { my($p_ref1, $p_ref2) = @_; my @polynomial1 = @$p_ref1; my @polynomial2 = @$p_ref2; return 1 if (scalar @polynomial1 != scalar @polynomial2); foreach my $c1 (@polynomial1) { my $c2 = shift @polynomial2; return 1 if ($c1 != $c2); } return 0; } # # (x + cplx(-3, 2)) * (x + cplx(3, 2)) = ? # my @c1x = (Math::Complex->new(-3, 2), 1); my @c1y = (Math::Complex->new(3, 2), 1); my @c1ans = (-13, Math::Complex->new(0, 4), 1 ); my $ans_ref = pl_mult(\@c1x, \@c1y); ok((polycmp($ans_ref, \@c1ans) == 0), " f() = [ " . join(", ", @c1x) . " ] * \n" . " f() = [ " . join(", ", @c1y) . " ] = \n" . " f'() = [ " . join(", ", @{$ans_ref}) . " ].\n" ); # # (x + cplx(-3, 2)) * (x + cplx(3, 2)) = ? # my @c2x = (Math::BigRat->new('3/2'), Math::BigRat->new('103/256'), 1); my @c2y = (Math::BigRat->new('7/2'), Math::BigRat->new('103/256'), 1); my @c2ans = ( Math::BigRat->new('21/4'), Math::BigRat->new('515/256'), Math::BigRat->new('338289/63536'), Math::BigRat->new('103/128'), 1 ); my $big_ref = pl_mult(\@c2x, \@c2y); ok((polycmp($ans_ref, \@c1ans) == 0), " f() = [ " . join(", ", @c2x) . " ] * \n" . " f() = [ " . join(", ", @c2y) . " ] = \n" . " f'() = [ " . join(", ", @{$big_ref}) . " ].\n" ); 1; Math-Utils-1.14/t/16-evaluate.t000555001750001750 245113647634102 16445 0ustar00jgamblejgamble000000000000# Before `make install' is performed this script should be runnable with # `make test'. After `make install' it should work as `perl 16-evaluate.t' use 5.010001; use Test::More tests => 8; use Math::Utils qw(:polynomial :compare); use Math::Complex; use strict; use warnings; my $fltcmp = generate_fltcmp(); my @case = ( [[1, 4, 6, 4, 1], [-1, -1, -1, -1]], [[-1, 0, 0, 0, 1], [root(1, 4)]], [[1, 0, 0, 0, 1], [root(-1, 4)]], [[24, -50, 35, -10, 1], [1, 2, 3, 4]], ); foreach (@case) { my @case = @$_; my @coef = @{$case[0]}; my @x = @{$case[1]}; my @y = pl_evaluate(\@coef, \@x); ok( (&$fltcmp($y[0], 0.0) == 0 and &$fltcmp($y[1], 0.0) == 0 and &$fltcmp($y[2], 0.0) == 0 and &$fltcmp($y[3], 0.0) == 0), " [ " . join(", ", @coef) . " ] returned" . " [ " . join(", ", @y) . " ]" ); } # # The above tests used an array ref for the X values. Test the other ways. # my $x = 3; my $cref = [8, -18, 5]; my @y; @y = pl_evaluate($cref, \$x); ok($y[0] == -1, "SCALAR ref of X variable failed."); @y = pl_evaluate($cref, $x); ok($y[0] == -1, "Simple use of X variable failed."); @y = pl_evaluate($cref, ($x, $x, $x, $x)); ok(join("", @y) eq "-1-1-1-1", "List of X variables failed."); @y = pl_evaluate($cref, [$x, $x], [$x, $x]); ok(join("", @y) eq "-1-1-1-1", "List of ARRAY refs failed."); 1; Math-Utils-1.14/t/17-derivative-eval.t000555001750001750 567413647634102 17741 0ustar00jgamblejgamble000000000000# Before `make install' is performed this script should be runnable with # `make test'. After `make install' it should work as `perl 17-derivative-eval.t' use 5.010001; use Test::More tests => 12; use Math::Utils qw(:polynomial :compare); use strict; use warnings; my(@coef, $y, $dy, $d2y); my $fltcmp = generate_fltcmp(); # # (13) # # # At point 5, even though the equation is a constant. # @coef = (13); ($y, $dy, $d2y) = pl_dxevaluate(\@coef, 5); ok( (&$fltcmp($y, 13) == 0 and &$fltcmp($dy, 0) == 0 and &$fltcmp($d2y, 0) == 0), " [ " . join(", ", @coef) . " ]"); # # (4, 21.5) # # (a linear equation). # # At point 5. # @coef = (-4, 21.5); ($y, $dy, $d2y) = pl_dxevaluate(\@coef, 5); ok( (&$fltcmp($y, 103.5) == 0 and &$fltcmp($dy, 21.5) == 0 and &$fltcmp($d2y, 0) == 0), " [ " . join(", ", @coef) . " ]"); # # (1, 0, 0, 0, -1) # # At point 5. # @coef = (-1, 0, 0, 0, 1); ($y, $dy, $d2y) = pl_dxevaluate(\@coef, 5); ok( (&$fltcmp($y, 624) == 0 and &$fltcmp($dy, 500) == 0 and &$fltcmp($d2y, 300) == 0), " [ " . join(", ", @coef) . " ]"); # # (1, 4, 6, 4, 1) # # At point 5. # @coef = (1, 4, 6, 4, 1); ($y, $dy, $d2y) = pl_dxevaluate(\@coef, 5); ok( (&$fltcmp($y, 1296) == 0 and &$fltcmp($dy, 864) == 0 and &$fltcmp($d2y, 432) == 0), " [ " . join(", ", @coef) . " ]"); # # (1, -10, 35, -50, 24) # # At point 5. # @coef = (24, -50, 35, -10, 1); ($y, $dy, $d2y) = pl_dxevaluate(\@coef, 5); ok( (&$fltcmp($y, 24) == 0 and &$fltcmp($dy, 50) == 0 and &$fltcmp($d2y, 70) == 0), " [ " . join(", ", @coef) . " ]"); # # (-31, 14, -16, -14, 1) # # At point 5 # @coef = (1, -14, -16, 14, -31); ($y, $dy, $d2y) = pl_dxevaluate(\@coef, 5); ok( (&$fltcmp($y, -18094) == 0 and &$fltcmp($dy, -14624) == 0 and &$fltcmp($d2y, -8912) == 0), " [ " . join(", ", @coef) . " ]"); # # (4, -20, -7, 49, -70, 7, -53, 90) # # At points 5, 3, 1, -1, -3, -5 # @coef = (90, -53, 7, -70, 49, -7, -20, 4); ($y, $dy, $d2y) = pl_dxevaluate(\@coef, 5); ok( (&$fltcmp($y, 0) == 0 and &$fltcmp($dy, 59892) == 0 and &$fltcmp($d2y, 145114) == 0), " [ " . join(", ", @coef) . " ]"); ($y, $dy, $d2y) = pl_dxevaluate(\@coef, 3); ok( (&$fltcmp($y, -5460) == 0 and &$fltcmp($dy, -8192) == 0 and &$fltcmp($d2y, -7510) == 0), " [ " . join(", ", @coef) . " ]"); ($y, $dy, $d2y) = pl_dxevaluate(\@coef, 1); ok( (&$fltcmp($y, 0) == 0 and &$fltcmp($dy, -180) == 0 and &$fltcmp($d2y, -390) == 0), " [ " . join(", ", @coef) . " ]"); ($y, $dy, $d2y) = pl_dxevaluate(\@coef, -1); ok( (&$fltcmp($y, 252) == 0 and &$fltcmp($dy, -360) == 0 and &$fltcmp($d2y, 394) == 0), " [ " . join(", ", @coef) . " ]"); ($y, $dy, $d2y) = pl_dxevaluate(\@coef, -3); ok( (&$fltcmp($y, -15456) == 0 and &$fltcmp($dy, 39460) == 0 and &$fltcmp($d2y, -79078) == 0), " [ " . join(", ", @coef) . " ]"); ($y, $dy, $d2y) = pl_dxevaluate(\@coef, -5); ok( (&$fltcmp($y, -563220) == 0 and &$fltcmp($dy, 760752) == 0 and &$fltcmp($d2y, -865686) == 0), " [ " . join(", ", @coef) . " ]"); 1; Math-Utils-1.14/t/18-translate.t000444001750001750 114113647634102 16626 0ustar00jgamblejgamble000000000000# Before `make install' is performed this script should be runnable with # `make test'. After `make install' it should work as `perl 16-evaluate.t' use 5.010001; use Test::More tests => 4; use Math::Utils qw(:polynomial); use Math::Complex; use strict; use warnings; my $x = [8, 3, 1]; my @case = ( [[1, 1], [12, 5, 1]], [[-1, 1], [6, 1, 1]], [[3, 1], [26, 9, 1]], [[-8, 0, 0, 1], [48, 0, 0, -13, 0, 0, 1]], ); foreach (@case) { my($y, $z) = @$_; my $ans = pl_translate($x, $y); is_deeply( $z, $ans, " y = [ " . join(", ", @$y) . " ] returned" . " [ " . join(", ", @$ans) . " ]" ); } 1; Math-Utils-1.14/t/30-finitedif.t000555001750001750 1375113647634102 16621 0ustar00jgamblejgamble000000000000#!perl -T use 5.010001; use strict; use warnings; use Test::More tests => 10; use Math::Utils qw(:polynomial :utility); # # Tests by creating polynomials from known sequences. # The sequences after the sum-of-powers tests are taken # from New Mathematical Diversions From Scientific American, # by Martin Gardner, chapter 20. # my($fc, $start, @seq); my($mult, $div, $p); # # Cubic 4 4 1 1 # $start = 0; @seq = (4, 10, 24, 52, 100); $fc = seq_difference(\@seq); ($mult, $div, $p) = make_poly($fc, $start); #diag("Cubic: $mult, $div, [", join(", ",@$p) . "]"); ok(($mult == 1 and $div == 1 and join("", @$p) eq "4411"), "Test Cubic 4 4 1 1"); # # Sum of powers, p = 1 (triangle numbers). # $start = 0; @seq = (0, 1, 3, 6, 10); $fc = seq_difference(\@seq); ($mult, $div, $p) = make_poly($fc, $start); #diag("Triangles: $mult, $div, [", join(", ",@$p) . "]"); ok(($mult == 1 and $div == 2 and join("", @$p) eq "011"), "Triangle numbers"); # # Sum of powers, p = 2 # $start = 0; @seq = (0, 1, 5, 14, 30, 55); $fc = seq_difference(\@seq); ($mult, $div, $p) = make_poly($fc, $start); #diag("Squares: $mult, $div, [", join(", ",@$p) . "]"); ok(($mult == 1 and $div == 6 and join("", @$p) eq "0132"), "Sum of squares."); # # Sum of powers, p = 3 # $start = 0; @seq = (0, 1, 9, 36, 100, 225); $fc = seq_difference(\@seq); ($mult, $div, $p) = make_poly($fc, $start); #diag("Cubics: $mult, $div, [", join(", ",@$p) . "]"); ok(($mult == 1 and $div == 4 and join("", @$p) eq "00121"), "Sum of cubics"); # # For each cut, what is the maximum number of pieces when slicing a circle. # $start = 0; @seq = (1, 2, 4, 7, 11); $fc = seq_difference(\@seq); ($mult, $div, $p) = make_poly($fc, $start); #diag("Circle cutting problem: $mult, $div, [", join(", ",@$p) . "]"); ok(($mult == 1 and $div == 2 and join(",", @$p) eq "2,1,1"), "Circle cutting problem"); # # Number of pieces produced by n plane cuts through a cylinder. # $start = 0; @seq = (1, 2, 4, 8, 15); $fc = seq_difference(\@seq); ($mult, $div, $p) = make_poly($fc, $start); #diag("Cylinder cutting problem: $mult, $div, [", join(", ",@$p) . "]"); ok(($mult == 1 and $div == 6 and join(",", @$p) eq "6,5,0,1"), "Cylinder cutting problem"); # # What is the maximum number of pieces produced by n simultaneous plane cuts # through a doughnut. # # There's ambiguity about what counts as a "piece" when there are zero cuts, # so start at one cut. # $start = 1; @seq = (2, 6, 13, 24); $fc = seq_difference(\@seq); ($mult, $div, $p) = make_poly($fc, $start); #diag("Doughnut cutting problem: $mult, $div, [", join(", ",@$p) . "]"); ok(($mult == 1 and $div == 6 and join(",", @$p) eq "0,8,3,1"), "Doughnut cutting problem"); # # What are the maximum number of triangles one can create when drawing n lines on paper. # $start = 1; @seq = (0, 0, 1, 4, 10); $fc = seq_difference(\@seq); ($mult, $div, $p) = make_poly($fc, $start); #diag("Triangle drawing problem: $mult, $div, [", join(", ",@$p) . "]"); ok(($mult == 1 and $div == 6 and join(",", @$p) eq "0,2,-3,1"), "Triangle drawing problem"); # # What are the maximum number of areas one can create by drawing n intersecting circles. # $start = 1; @seq = (2, 4, 8, 14); $fc = seq_difference(\@seq); ($mult, $div, $p) = make_poly($fc, $start); #diag("Circle drawing problem: $mult, $div, [", join(", ",@$p) . "]"); ok(($mult == 1 and $div == 1 and join(",", @$p) eq "2,-1,1"), "Circle drawing problem"); # # What are the maximum number of regions of space one can create by through n intersecting spheres. # $start = 1; @seq = (2, 4, 8, 16); $fc = seq_difference(\@seq); ($mult, $div, $p) = make_poly($fc, $start); #diag("Intersecting spheres problem: $mult, $div, [", join(", ",@$p) . "]"); ok(($mult == 1 and $div == 3 and join(",", @$p) eq "0,8,-3,1"), "Intersecting spheres problem"); #print_diff_triangle(seq_difference(\@seq, triangle => 1)); #print "\nDifference column:\n", join(", ", @$fc), "\n"; #print "Polynomial is: [", join(", ", @{$p}), "]/$m\n"; # # Healing wait in turns per level in the game Rogue (unfortunately, resulted in a messy polynomial). # #$start = 1; #@seq = ( 20, 18, 17, 14, 13, 10, 9, 8, 7, 4, 3, 2); exit (0); # # using the first column of the difference triangle, create the polynomial. # sub make_poly { my($seq, $startfrom) = @_; my(@diffs) = @$seq; my $n = $#diffs; my $p = [1]; my($mult, $div) = (1, 1); # # Set up the 1, x, x(x-1), x(x-1)(x-2), ... etc. polynomial sequence. # my @seq = ($p); for my $k (0 .. $n) { $seq[$k] = [ map($_ * $diffs[$k], @{$p}) ]; $p = pl_mult($p, [-($startfrom + $k), 1]); } # # Add the sequences together to get one polynomial. # my $m = 1; $p = [0]; for my $k (reverse 1 .. $#diffs) { my $sk = [map($_ * $m, @{ $seq[$k] })]; $p = pl_add($p, $sk); $m *= $k; } $p = pl_add($p, [$m * $diffs[0]]); # # Now find common factors. # my(@coefs) = grep($_ != 0, @{$p}); if (scalar @coefs) { $mult = gcd(@coefs); my $d = gcd($mult, $m); $p = [map($_/$mult, @{$p})]; $mult /= $d; $div = $m / $d; } return ($mult, $div, $p); } sub print_diff_triangle { my(@diffs) = @_; for my $j (0 .. $#diffs) { my(@v) = @{$diffs[$j]}; print join(" ", map(sprintf("%10d", $_), @v)), "\n"; } } #sub print_poly_sequence #{ # my(@seq) = @_; # # my $idx = 0; # print "\nThe polynomial sequences:\n"; # for my $q (@seq) # { # printf("%2d: [%s] / %d!\n", # $idx, # join(", ", @{$q}), # $idx); # $idx++; # } # print "\n"; #} # # $first_col = seq_difference([0, 1, 2, 4, 7, 13, 24]); # $diff_triangle = seq_difference([0, 1, 2, 4, 7, 13, 24], triangle => 1); # sub seq_difference { my($seq, %opt) = @_; my(@numbers) = @$seq; my $triangle = (exists $opt{triangle} and $opt{triangle} != 0)? 1: 0; my $n = $#numbers; my(@diffs) = ($numbers[0]); # # Create a new row by subracting number j from number j+1. # for my $j (1 .. $n) { my @v; push @v, $numbers[$_] - $numbers[$_ - 1] for (1 .. $#numbers); # # If it's a row of zeros, we're done anyway. # last unless (scalar grep($_ != 0, @v)); push @diffs, ($triangle)? [@v]: $v[0]; @numbers = @v; } return \@diffs; } Math-Utils-1.14/t/manifest.t000555001750001750 50713647634102 16201 0ustar00jgamblejgamble000000000000#!perl -T use 5.006; use strict; use warnings FATAL => 'all'; use Test::More; unless ( $ENV{RELEASE_TESTING} ) { plan( skip_all => "Author tests not required for installation" ); } my $min_tcm = 0.9; eval "use Test::CheckManifest $min_tcm"; plan skip_all => "Test::CheckManifest $min_tcm required" if $@; ok_manifest(); Math-Utils-1.14/t/pod.t000555001750001750 40113647634102 15146 0ustar00jgamblejgamble000000000000#!perl -T use 5.006; use strict; use warnings FATAL => 'all'; use Test::More; # Ensure a recent version of Test::Pod my $min_tp = 1.22; eval "use Test::Pod $min_tp"; plan skip_all => "Test::Pod $min_tp required for testing POD" if $@; all_pod_files_ok();