This is an automated email from the ASF dual-hosted git repository. erans pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/commons-numbers.git
commit 151ea6bbbd9ecbaf5948213adfda77977cae8400 Author: Gilles Sadowski <gil...@harfang.homelinux.org> AuthorDate: Tue Jun 4 03:53:43 2019 +0200 NUMBERS-112: Implement Brent's algorithm for finding the zero of a function. New maven module created. Code copied and adapted from "Commons Statistics" (where it was ported from "Commons Math"). --- commons-numbers-rootfinder/LICENSE.txt | 201 ++++++++++++++++ commons-numbers-rootfinder/NOTICE.txt | 5 + commons-numbers-rootfinder/README.md | 98 ++++++++ commons-numbers-rootfinder/pom.xml | 52 ++++ .../commons/numbers/rootfinder/BrentSolver.java | 239 ++++++++++++++++++ .../numbers/rootfinder/SolverException.java | 55 +++++ .../commons/numbers/rootfinder/package-info.java | 20 ++ .../src/site/resources/profile.jacoco | 17 ++ commons-numbers-rootfinder/src/site/site.xml | 35 +++ commons-numbers-rootfinder/src/site/xdoc/index.xml | 40 ++++ .../numbers/rootfinder/BrentSolverTest.java | 266 +++++++++++++++++++++ .../numbers/rootfinder/MonitoredFunction.java | 52 ++++ .../numbers/rootfinder/QuinticFunction.java | 29 +++ .../org/apache/commons/numbers/rootfinder/Sin.java | 29 +++ pom.xml | 1 + 15 files changed, 1139 insertions(+) diff --git a/commons-numbers-rootfinder/LICENSE.txt b/commons-numbers-rootfinder/LICENSE.txt new file mode 100644 index 0000000..261eeb9 --- /dev/null +++ b/commons-numbers-rootfinder/LICENSE.txt @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/commons-numbers-rootfinder/NOTICE.txt b/commons-numbers-rootfinder/NOTICE.txt new file mode 100644 index 0000000..b4ce061 --- /dev/null +++ b/commons-numbers-rootfinder/NOTICE.txt @@ -0,0 +1,5 @@ +Apache Commons Numbers +Copyright 2001-2019 The Apache Software Foundation + +This product includes software developed at +The Apache Software Foundation (http://www.apache.org/). diff --git a/commons-numbers-rootfinder/README.md b/commons-numbers-rootfinder/README.md new file mode 100644 index 0000000..aa902d6 --- /dev/null +++ b/commons-numbers-rootfinder/README.md @@ -0,0 +1,98 @@ +<!--- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<!--- + +======================================================================+ + |**** ****| + |**** THIS FILE IS GENERATED BY THE COMMONS BUILD PLUGIN ****| + |**** DO NOT EDIT DIRECTLY ****| + |**** ****| + +======================================================================+ + | TEMPLATE FILE: readme-md-template.md | + | commons-build-plugin/trunk/src/main/resources/commons-xdoc-templates | + +======================================================================+ + | | + | 1) Re-generate using: mvn commons:readme-md | + | | + | 2) Set the following properties in the component's pom: | + | - commons.componentid (required, alphabetic, lower case) | + | - commons.release.version (required) | + | | + | 3) Example Properties | + | | + | <properties> | + | <commons.componentid>math</commons.componentid> | + | <commons.release.version>1.2</commons.release.version> | + | </properties> | + | | + +======================================================================+ +---> +Apache Commons Numbers Root Finder +=================== + +Root finding utilities. + +Documentation +------------- + +More information can be found on the [homepage](https://commons.apache.org/proper/commons-numbers). +The [JavaDoc](https://commons.apache.org/proper/commons-numbers/javadocs/api-release) can be browsed. +Questions related to the usage of Apache Commons Numbers Root Finder should be posted to the [user mailing list][ml]. + +Where can I get the latest release? +----------------------------------- +You can download source and binaries from our [download page](https://commons.apache.org/proper/commons-numbers/download_numbers.cgi). + +Alternatively you can pull it from the central Maven repositories: + +```xml +<dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-numbers-rootfinder</artifactId> + <version>1.0</version> +</dependency> +``` + +Contributing +------------ + +We accept PRs via github. The [developer mailing list][ml] is the main channel of communication for contributors. +There are some guidelines which will make applying PRs easier for us: ++ No tabs! Please use spaces for indentation. ++ Respect the code style. ++ Create minimal diffs - disable on save actions like reformat source code or organize imports. If you feel the source code should be reformatted create a separate PR for this change. ++ Provide JUnit tests for your changes and make sure your changes don't break any existing tests by running ```mvn clean test```. + +If you plan to contribute on a regular basis, please consider filing a [contributor license agreement](https://www.apache.org/licenses/#clas). +You can learn more about contributing via GitHub in our [contribution guidelines](CONTRIBUTING.md). + +License +------- +Code is under the [Apache Licence v2](https://www.apache.org/licenses/LICENSE-2.0.txt). + +Donations +--------- +You like Apache Commons Numbers Root Finder? Then [donate back to the ASF](https://www.apache.org/foundation/contributing.html) to support the development. + +Additional Resources +-------------------- + ++ [Apache Commons Homepage](https://commons.apache.org/) ++ [Apache Bugtracker (JIRA)](https://issues.apache.org/jira/) ++ [Apache Commons Twitter Account](https://twitter.com/ApacheCommons) ++ #apachecommons IRC channel on freenode.org + +[ml]:https://commons.apache.org/mail-lists.html diff --git a/commons-numbers-rootfinder/pom.xml b/commons-numbers-rootfinder/pom.xml new file mode 100644 index 0000000..90465c8 --- /dev/null +++ b/commons-numbers-rootfinder/pom.xml @@ -0,0 +1,52 @@ +<?xml version="1.0"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" + xmlns="http://maven.apache.org/POM/4.0.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <modelVersion>4.0.0</modelVersion> + + <parent> + <groupId>org.apache.commons</groupId> + <artifactId>commons-numbers-parent</artifactId> + <version>1.0-SNAPSHOT</version> + </parent> + + <artifactId>commons-numbers-root-finder</artifactId> + <name>Apache Commons Numbers Root Finder</name> + + <description>Root finding utilities.</description> + + <properties> + <!-- The Java Module System Name --> + <commons.module.name>org.apache.commons.numbers.rootfinder</commons.module.name> + <!-- This value must reflect the current name of the base package. --> + <commons.osgi.symbolicName>org.apache.commons.numbers.rootfinder</commons.osgi.symbolicName> + <!-- OSGi --> + <commons.osgi.export>org.apache.commons.numbers.rootfinder</commons.osgi.export> + <!-- Workaround to avoid duplicating config files. --> + <numbers.parent.dir>${basedir}/..</numbers.parent.dir> + </properties> + + <dependencies> + <dependency> + <groupId>org.apache.commons</groupId> + <artifactId>commons-numbers-core</artifactId> + </dependency> + </dependencies> + +</project> diff --git a/commons-numbers-rootfinder/src/main/java/org/apache/commons/numbers/rootfinder/BrentSolver.java b/commons-numbers-rootfinder/src/main/java/org/apache/commons/numbers/rootfinder/BrentSolver.java new file mode 100644 index 0000000..493985f --- /dev/null +++ b/commons-numbers-rootfinder/src/main/java/org/apache/commons/numbers/rootfinder/BrentSolver.java @@ -0,0 +1,239 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.numbers.rootfinder; + +import java.util.function.DoubleUnaryOperator; +import org.apache.commons.numbers.core.Precision; + +/** + * This class implements the <a href="http://mathworld.wolfram.com/BrentsMethod.html"> + * Brent algorithm</a> for finding zeros of real univariate functions. + * The function should be continuous but not necessarily smooth. + * The {@code solve} method returns a zero {@code x} of the function {@code f} + * in the given interval {@code [a, b]} to within a tolerance + * {@code 2 eps abs(x) + t} where {@code eps} is the relative accuracy and + * {@code t} is the absolute accuracy. + * <p>The given interval must bracket the root.</p> + * <p> + * The reference implementation is given in chapter 4 of + * <blockquote> + * <b>Algorithms for Minimization Without Derivatives</b>, + * <em>Richard P. Brent</em>, + * Dover, 2002 + * </blockquote> + */ +public class BrentSolver { + /** Relative accuracy. */ + private final double relativeAccuracy; + /** Absolutee accuracy. */ + private final double absoluteAccuracy; + /** Function accuracy. */ + private final double functionValueAccuracy; + + /** + * Construct a solver. + * + * @param relativeAccuracy Relative accuracy. + * @param absoluteAccuracy Absolute accuracy. + * @param functionValueAccuracy Function value accuracy. + */ + public BrentSolver(double relativeAccuracy, + double absoluteAccuracy, + double functionValueAccuracy) { + this.relativeAccuracy = relativeAccuracy; + this.absoluteAccuracy = absoluteAccuracy; + this.functionValueAccuracy = functionValueAccuracy; + } + + /** + * Search the function's zero within the given interval. + * + * @param func Function to solve. + * @param min Lower bound. + * @param max Upper bound. + * @return the root. + */ + public double findRoot(DoubleUnaryOperator func, + double min, + double max) { + return findRoot(func, min, 0.5 * (min + max), max); + } + + /** + * Search the function's zero within the given interval, + * starting from the given estimate. + * + * @param func Function to solve. + * @param min Lower bound. + * @param initial Initial guess. + * @param max Upper bound. + * @return the root. + */ + public double findRoot(DoubleUnaryOperator func, + double min, + double initial, + double max) { + if (min > max) { + throw new SolverException(SolverException.TOO_LARGE, min, max); + } + if (initial < min || + initial > max) { + throw new SolverException(SolverException.OUT_OF_RANGE, initial, min, max); + } + + // Return the initial guess if it is good enough. + final double yInitial = func.applyAsDouble(initial); + if (Math.abs(yInitial) <= functionValueAccuracy) { + return initial; + } + + // Return the first endpoint if it is good enough. + final double yMin = func.applyAsDouble(min); + if (Math.abs(yMin) <= functionValueAccuracy) { + return min; + } + + // Reduce interval if min and initial bracket the root. + if (yInitial * yMin < 0) { + return brent(func, min, initial, yMin, yInitial); + } + + // Return the second endpoint if it is good enough. + final double yMax = func.applyAsDouble(max); + if (Math.abs(yMax) <= functionValueAccuracy) { + return max; + } + + // Reduce interval if initial and max bracket the root. + if (yInitial * yMax < 0) { + return brent(func, initial, max, yInitial, yMax); + } + + throw new SolverException(SolverException.BRACKETING, min, yMin, max, yMax); + } + + /** + * Search for a zero inside the provided interval. + * This implementation is based on the algorithm described at page 58 of + * the book + * <blockquote> + * <b>Algorithms for Minimization Without Derivatives</b>, + * <i>Richard P. Brent</i>, + * Dover 0-486-41998-3 + * </blockquote> + * + * @param func Function to solve. + * @param lo Lower bound of the search interval. + * @param hi Higher bound of the search interval. + * @param fLo Function value at the lower bound of the search interval. + * @param fHi Function value at the higher bound of the search interval. + * @return the value where the function is zero. + */ + private double brent(DoubleUnaryOperator func, + double lo, double hi, + double fLo, double fHi) { + double a = lo; + double fa = fLo; + double b = hi; + double fb = fHi; + double c = a; + double fc = fa; + double d = b - a; + double e = d; + + final double t = absoluteAccuracy; + final double eps = relativeAccuracy; + + while (true) { + if (Math.abs(fc) < Math.abs(fb)) { + a = b; + b = c; + c = a; + fa = fb; + fb = fc; + fc = fa; + } + + final double tol = 2 * eps * Math.abs(b) + t; + final double m = 0.5 * (c - b); + + if (Math.abs(m) <= tol || + Precision.equals(fb, 0)) { + return b; + } + if (Math.abs(e) < tol || + Math.abs(fa) <= Math.abs(fb)) { + // Force bisection. + d = m; + e = d; + } else { + double s = fb / fa; + double p; + double q; + // The equality test (a == c) is intentional, + // it is part of the original Brent's method and + // it should NOT be replaced by proximity test. + if (a == c) { + // Linear interpolation. + p = 2 * m * s; + q = 1 - s; + } else { + // Inverse quadratic interpolation. + q = fa / fc; + final double r = fb / fc; + p = s * (2 * m * q * (q - r) - (b - a) * (r - 1)); + q = (q - 1) * (r - 1) * (s - 1); + } + if (p > 0) { + q = -q; + } else { + p = -p; + } + s = e; + e = d; + if (p >= 1.5 * m * q - Math.abs(tol * q) || + p >= Math.abs(0.5 * s * q)) { + // Inverse quadratic interpolation gives a value + // in the wrong direction, or progress is slow. + // Fall back to bisection. + d = m; + e = d; + } else { + d = p / q; + } + } + a = b; + fa = fb; + + if (Math.abs(d) > tol) { + b += d; + } else if (m > 0) { + b += tol; + } else { + b -= tol; + } + fb = func.applyAsDouble(b); + if ((fb > 0 && fc > 0) || + (fb <= 0 && fc <= 0)) { + c = a; + fc = fa; + d = b - a; + e = d; + } + } + } +} diff --git a/commons-numbers-rootfinder/src/main/java/org/apache/commons/numbers/rootfinder/SolverException.java b/commons-numbers-rootfinder/src/main/java/org/apache/commons/numbers/rootfinder/SolverException.java new file mode 100644 index 0000000..c35f2fe --- /dev/null +++ b/commons-numbers-rootfinder/src/main/java/org/apache/commons/numbers/rootfinder/SolverException.java @@ -0,0 +1,55 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.numbers.rootfinder; + +import java.text.MessageFormat; + +/** + * Package private exception class with constants for frequently used messages. + */ +class SolverException extends IllegalArgumentException { + /** Error message for "too large" condition. */ + static final String TOO_LARGE = "{0} > {1}"; + /** Error message for "out of range" condition. */ + static final String OUT_OF_RANGE = "{0} is out of range [{1}, {2}]"; + /** Error message for "failed bracketing" condition. */ + static final String BRACKETING = "No bracketing: f({0})={1}, f({2})={3}"; + + /** Serializable version identifier. */ + private static final long serialVersionUID = 20190602L; + + /** Arguments for formatting the message. */ + private final Object[] formatArguments; + + /** + * Create an exception where the message is constructed by applying + * the {@code format()} method from {@code java.text.MessageFormat}. + * + * @param message the exception message with replaceable parameters + * @param formatArguments the arguments for formatting the message + */ + SolverException(String message, Object... formatArguments) { + super(message); + this.formatArguments = formatArguments; + } + + /** {@inheritDoc} */ + @Override + public String getMessage() { + return MessageFormat.format(super.getMessage(), formatArguments); + } +} diff --git a/commons-numbers-rootfinder/src/main/java/org/apache/commons/numbers/rootfinder/package-info.java b/commons-numbers-rootfinder/src/main/java/org/apache/commons/numbers/rootfinder/package-info.java new file mode 100644 index 0000000..5fb3a3a --- /dev/null +++ b/commons-numbers-rootfinder/src/main/java/org/apache/commons/numbers/rootfinder/package-info.java @@ -0,0 +1,20 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Root finding utilities. + */ +package org.apache.commons.numbers.rootfinder; diff --git a/commons-numbers-rootfinder/src/site/resources/profile.jacoco b/commons-numbers-rootfinder/src/site/resources/profile.jacoco new file mode 100644 index 0000000..a12755f --- /dev/null +++ b/commons-numbers-rootfinder/src/site/resources/profile.jacoco @@ -0,0 +1,17 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (the "License"); you may not use this file except in compliance with +# the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ----------------------------------------------------------------------------- +# +# Empty file used to automatically trigger JaCoCo profile from commons parent pom diff --git a/commons-numbers-rootfinder/src/site/site.xml b/commons-numbers-rootfinder/src/site/site.xml new file mode 100644 index 0000000..454d015 --- /dev/null +++ b/commons-numbers-rootfinder/src/site/site.xml @@ -0,0 +1,35 @@ +<?xml version="1.0" encoding="ISO-8859-1"?> +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> +<project name="Numbers"> + <bannerRight> + <name>Apache Commons Numbers</name> + <src>/images/commons_numbers.small.png</src> + <href>/index.html</href> + </bannerRight> + + <body> + <menu name="Numbers Root Finder"> + <item name="Overview" href="index.html"/> + <item name="Latest API docs (development)" + href="apidocs/index.html"/> + <!--item name="Javadoc (1.0 release)" + href="http://commons.apache.org/rng/commons-numbers-rootfinder/javadocs/api-1.0/index.html"/--> + </menu> + + </body> +</project> diff --git a/commons-numbers-rootfinder/src/site/xdoc/index.xml b/commons-numbers-rootfinder/src/site/xdoc/index.xml new file mode 100644 index 0000000..8979130 --- /dev/null +++ b/commons-numbers-rootfinder/src/site/xdoc/index.xml @@ -0,0 +1,40 @@ +<?xml version="1.0"?> + +<!-- + Licensed to the Apache Software Foundation (ASF) under one or more + contributor license agreements. See the NOTICE file distributed with + this work for additional information regarding copyright ownership. + The ASF licenses this file to You under the Apache License, Version 2.0 + (the "License"); you may not use this file except in compliance with + the License. You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + --> + +<document> + + <properties> + <title>Commons Numbers Root Finder</title> + </properties> + + <body> + + <section name="Apache Commons Numbers: Number types" href="summary"> + <p> + Commons Numbers provides utilities such as complex numbers and fractions. + </p> + + <p> + The "rootfinder" module contains utilities for finding the zero of a function. + </p> + </section> + + </body> + +</document> diff --git a/commons-numbers-rootfinder/src/test/java/org/apache/commons/numbers/rootfinder/BrentSolverTest.java b/commons-numbers-rootfinder/src/test/java/org/apache/commons/numbers/rootfinder/BrentSolverTest.java new file mode 100644 index 0000000..b414f6a --- /dev/null +++ b/commons-numbers-rootfinder/src/test/java/org/apache/commons/numbers/rootfinder/BrentSolverTest.java @@ -0,0 +1,266 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with this + * work for additional information regarding copyright ownership. The ASF + * licenses this file to You under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law + * or agreed to in writing, software distributed under the License is + * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the specific language + * governing permissions and limitations under the License. + */ +package org.apache.commons.numbers.rootfinder; + +import java.util.function.DoubleUnaryOperator; +import org.junit.Assert; +import org.junit.Test; + +/** + * Test cases for the {@link BrentSolver} class. + */ +public class BrentSolverTest { + private static final double DEFAULT_ABSOLUTE_ACCURACY = 1e-6; + private static final double DEFAULT_RELATIVE_ACCURACY = 1e-14; + private static final double DEFAULT_FUNCTION_ACCURACY = 1e-15; + + @Test + public void testSinZero() { + // The sinus function is behaved well around the root at pi. The second + // order derivative is zero, which means linar approximating methods will + // still converge quadratically. + final DoubleUnaryOperator func = new Sin(); + final BrentSolver solver = new BrentSolver(DEFAULT_ABSOLUTE_ACCURACY, + DEFAULT_RELATIVE_ACCURACY, + DEFAULT_FUNCTION_ACCURACY); + + double result; + MonitoredFunction f; + + // Somewhat benign interval. The function is monotonous. + f = new MonitoredFunction(func); + result = solver.findRoot(f, 3, 4); + Assert.assertEquals(result, Math.PI, DEFAULT_ABSOLUTE_ACCURACY); + Assert.assertTrue(f.getCallsCount() <= 7); + + // Larger and somewhat less benign interval. The function is grows first. + f = new MonitoredFunction(func); + result = solver.findRoot(f, 1, 4); + Assert.assertEquals(result, Math.PI, DEFAULT_ABSOLUTE_ACCURACY); + Assert.assertTrue(f.getCallsCount() <= 8); + } + + @Test + public void testQuinticZero() { + // The quintic function has zeros at 0, +-0.5 and +-1. + // Around the root of 0 the function is well behaved, with a second derivative + // of zero a 0. + // The other roots are less well to find, in particular the root at 1, because + // the function grows fast for x>1. + // The function has extrema (first derivative is zero) at 0.27195613 and 0.82221643, + // intervals containing these values are harder for the solvers. + final DoubleUnaryOperator func = new QuinticFunction(); + final BrentSolver solver = new BrentSolver(DEFAULT_ABSOLUTE_ACCURACY, + DEFAULT_RELATIVE_ACCURACY, + DEFAULT_FUNCTION_ACCURACY); + + double result; + MonitoredFunction f; + + // Symmetric bracket around 0. Test whether solvers can handle hitting + // the root in the first iteration. + f = new MonitoredFunction(func); + result = solver.findRoot(f, -0.2, 0.2); + Assert.assertEquals(result, 0, DEFAULT_ABSOLUTE_ACCURACY); + Assert.assertTrue(f.getCallsCount() <= 3); + + // 1 iterations on i586 JDK 1.4.1. + // Asymmetric bracket around 0. Contains extremum. + f = new MonitoredFunction(func); + result = solver.findRoot(f, -0.1, 0.3); + Assert.assertEquals(result, 0, DEFAULT_ABSOLUTE_ACCURACY); + // 5 iterations on i586 JDK 1.4.1. + Assert.assertTrue(f.getCallsCount() <= 7); + + // Large bracket around 0. Contains two extrema. + f = new MonitoredFunction(func); + result = solver.findRoot(f, -0.3, 0.45); + Assert.assertEquals(result, 0, DEFAULT_ABSOLUTE_ACCURACY); + // 6 iterations on i586 JDK 1.4.1. + Assert.assertTrue(f.getCallsCount() <= 8); + + // Benign bracket around 0.5, function is monotonous. + f = new MonitoredFunction(func); + result = solver.findRoot(f, 0.3, 0.7); + Assert.assertEquals(0.5, result, DEFAULT_ABSOLUTE_ACCURACY); + // 6 iterations on i586 JDK 1.4.1. + Assert.assertTrue(f.getCallsCount() <= 9); + + // Less benign bracket around 0.5, contains one extremum. + f = new MonitoredFunction(func); + result = solver.findRoot(f, 0.2, 0.6); + Assert.assertEquals(0.5, result, DEFAULT_ABSOLUTE_ACCURACY); + Assert.assertTrue(f.getCallsCount() <= 10); + + // Large, less benign bracket around 0.5, contains both extrema. + f = new MonitoredFunction(func); + result = solver.findRoot(f, 0.05, 0.95); + Assert.assertEquals(0.5, result, DEFAULT_ABSOLUTE_ACCURACY); + Assert.assertTrue(f.getCallsCount() <= 11); + + // Relatively benign bracket around 1, function is monotonous. Fast growth for x>1 + // is still a problem. + f = new MonitoredFunction(func); + result = solver.findRoot(f, 0.85, 1.25); + Assert.assertEquals(1.0, result, DEFAULT_ABSOLUTE_ACCURACY); + Assert.assertTrue(f.getCallsCount() <= 11); + + // Less benign bracket around 1 with extremum. + f = new MonitoredFunction(func); + result = solver.findRoot(f, 0.8, 1.2); + Assert.assertEquals(1.0, result, DEFAULT_ABSOLUTE_ACCURACY); + Assert.assertTrue(f.getCallsCount() <= 11); + + // Large bracket around 1. Monotonous. + f = new MonitoredFunction(func); + result = solver.findRoot(f, 0.85, 1.75); + Assert.assertEquals(1.0, result, DEFAULT_ABSOLUTE_ACCURACY); + Assert.assertTrue(f.getCallsCount() <= 13); + + // Large bracket around 1. Interval contains extremum. + f = new MonitoredFunction(func); + result = solver.findRoot(f, 0.55, 1.45); + Assert.assertEquals(1.0, result, DEFAULT_ABSOLUTE_ACCURACY); + Assert.assertTrue(f.getCallsCount() <= 10); + } + + @Test + public void testTooManyCalls() { + final DoubleUnaryOperator func = new QuinticFunction(); + final BrentSolver solver = new BrentSolver(DEFAULT_ABSOLUTE_ACCURACY, + DEFAULT_RELATIVE_ACCURACY, + DEFAULT_FUNCTION_ACCURACY); + + double result; + MonitoredFunction f; + + // Very large bracket around 1 for testing fast growth behaviour. + f = new MonitoredFunction(func); + result = solver.findRoot(f, 0.85, 5); + Assert.assertEquals(1.0, result, DEFAULT_ABSOLUTE_ACCURACY); + Assert.assertTrue(f.getCallsCount() <= 15); + + try { + f = new MonitoredFunction(func, 10); + result = solver.findRoot(f, 0.85, 5); + Assert.fail("Expected too many calls condition"); + } catch (IllegalStateException ex) { + // Expected. + // Ensure expected error condition. + Assert.assertFalse(ex.getMessage().indexOf("too many calls") == -1); + } + } + + @Test + public void testRootEndpoints() { + final DoubleUnaryOperator f = new Sin(); + final BrentSolver solver = new BrentSolver(DEFAULT_ABSOLUTE_ACCURACY, + DEFAULT_RELATIVE_ACCURACY, + DEFAULT_FUNCTION_ACCURACY); + + // Endpoint is root. + double result = solver.findRoot(f, Math.PI, 4); + Assert.assertEquals(Math.PI, result, DEFAULT_ABSOLUTE_ACCURACY); + + result = solver.findRoot(f, 3, Math.PI); + Assert.assertEquals(Math.PI, result, DEFAULT_ABSOLUTE_ACCURACY); + + result = solver.findRoot(f, Math.PI, 3.5, 4); + Assert.assertEquals(Math.PI, result, DEFAULT_ABSOLUTE_ACCURACY); + + result = solver.findRoot(f, 3, 3.07, Math.PI); + Assert.assertEquals(Math.PI, result, DEFAULT_ABSOLUTE_ACCURACY); + } + + @Test + public void testBadEndpoints() { + final DoubleUnaryOperator f = new Sin(); + final BrentSolver solver = new BrentSolver(DEFAULT_ABSOLUTE_ACCURACY, + DEFAULT_RELATIVE_ACCURACY, + DEFAULT_FUNCTION_ACCURACY); + try { // Bad interval. + solver.findRoot(f, 1, -1); + Assert.fail("Expecting bad interval condition"); + } catch (SolverException ex) { + // Ensure expected error condition. + Assert.assertFalse(ex.getMessage().indexOf(" > ") == -1); + } + try { // No bracketing. + solver.findRoot(f, 1, 1.5); + Assert.fail("Expecting non-bracketing condition"); + } catch (SolverException ex) { + // Ensure expected error condition. + Assert.assertFalse(ex.getMessage().indexOf("No bracketing") == -1); + } + try { // No bracketing. + solver.findRoot(f, 1, 1.2, 1.5); + Assert.fail("Expecting non-bracketing condition"); + } catch (SolverException ex) { + // Ensure expected error condition. + Assert.assertFalse(ex.getMessage().indexOf("No bracketing") == -1); + } + } + + @Test + public void testBadInitialGuess() { + final DoubleUnaryOperator func = new QuinticFunction(); + final BrentSolver solver = new BrentSolver(DEFAULT_ABSOLUTE_ACCURACY, + DEFAULT_RELATIVE_ACCURACY, + DEFAULT_FUNCTION_ACCURACY); + + try { + // Invalid guess (it *is* a root, but outside of the range). + double result = solver.findRoot(func, 0.0, 7.0, 0.6); + Assert.fail("an out of range condition was expected"); + } catch (SolverException ex) { + // Ensure expected error condition. + Assert.assertFalse(ex.getMessage().indexOf("out of range") == -1); + } + } + + @Test + public void testInitialGuess() { + final DoubleUnaryOperator func = new QuinticFunction(); + final BrentSolver solver = new BrentSolver(DEFAULT_ABSOLUTE_ACCURACY, + DEFAULT_RELATIVE_ACCURACY, + DEFAULT_FUNCTION_ACCURACY); + double result; + MonitoredFunction f; + + // No guess. + f = new MonitoredFunction(func); + result = solver.findRoot(f, 0.6, 7.0); + Assert.assertEquals(1.0, result, DEFAULT_ABSOLUTE_ACCURACY); + final int referenceCallsCount = f.getCallsCount(); + Assert.assertTrue(referenceCallsCount >= 13); + + // Bad guess. + f = new MonitoredFunction(func); + result = solver.findRoot(f, 0.6, 0.61, 7.0); + Assert.assertEquals(1.0, result, DEFAULT_ABSOLUTE_ACCURACY); + Assert.assertTrue(f.getCallsCount() > referenceCallsCount); + + // Good guess. + f = new MonitoredFunction(func); + result = solver.findRoot(f, 0.6, 0.9999990001, 7.0); + Assert.assertEquals(1.0, result, DEFAULT_ABSOLUTE_ACCURACY); + Assert.assertTrue(f.getCallsCount() < referenceCallsCount); + + // Perfect guess. + f = new MonitoredFunction(func); + result = solver.findRoot(f, 0.6, 1.0, 7.0); + Assert.assertEquals(1.0, result, DEFAULT_ABSOLUTE_ACCURACY); + Assert.assertEquals(1, f.getCallsCount()); + } +} diff --git a/commons-numbers-rootfinder/src/test/java/org/apache/commons/numbers/rootfinder/MonitoredFunction.java b/commons-numbers-rootfinder/src/test/java/org/apache/commons/numbers/rootfinder/MonitoredFunction.java new file mode 100644 index 0000000..04c4e03 --- /dev/null +++ b/commons-numbers-rootfinder/src/test/java/org/apache/commons/numbers/rootfinder/MonitoredFunction.java @@ -0,0 +1,52 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.numbers.rootfinder; + +import java.util.function.DoubleUnaryOperator; + +/** + * Wrapper class for counting functions calls. + */ +class MonitoredFunction implements DoubleUnaryOperator { + final int maxCount; + private int callsCount; + private final DoubleUnaryOperator f; + + public MonitoredFunction(DoubleUnaryOperator f) { + this(f, Integer.MAX_VALUE); + } + + public MonitoredFunction(DoubleUnaryOperator f, + int maxCount) { + callsCount = 0; + this.f = f; + this.maxCount = maxCount; + } + + public int getCallsCount() { + return callsCount; + } + + @Override + public double applyAsDouble(double x) { + if (++callsCount > maxCount) { + throw new IllegalStateException(callsCount + " > " + maxCount + + ": too many calls"); + } + return f.applyAsDouble(x); + } +} diff --git a/commons-numbers-rootfinder/src/test/java/org/apache/commons/numbers/rootfinder/QuinticFunction.java b/commons-numbers-rootfinder/src/test/java/org/apache/commons/numbers/rootfinder/QuinticFunction.java new file mode 100644 index 0000000..4385cf3 --- /dev/null +++ b/commons-numbers-rootfinder/src/test/java/org/apache/commons/numbers/rootfinder/QuinticFunction.java @@ -0,0 +1,29 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.numbers.rootfinder; + +import java.util.function.DoubleUnaryOperator; + +/** + * Auxiliary class for testing solvers. + */ +class QuinticFunction implements DoubleUnaryOperator { + @Override + public double applyAsDouble(double x) { + return (x - 1) * (x - 0.5) * x * (x + 0.5) * (x + 1); + } +} diff --git a/commons-numbers-rootfinder/src/test/java/org/apache/commons/numbers/rootfinder/Sin.java b/commons-numbers-rootfinder/src/test/java/org/apache/commons/numbers/rootfinder/Sin.java new file mode 100644 index 0000000..e569c05 --- /dev/null +++ b/commons-numbers-rootfinder/src/test/java/org/apache/commons/numbers/rootfinder/Sin.java @@ -0,0 +1,29 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.commons.numbers.rootfinder; + +import java.util.function.DoubleUnaryOperator; + +/** + * Auxiliary class for testing solvers. + */ +class Sin implements DoubleUnaryOperator { + @Override + public double applyAsDouble(double x) { + return Math.sin(x); + } +} diff --git a/pom.xml b/pom.xml index b3d5dff..c22e030 100644 --- a/pom.xml +++ b/pom.xml @@ -628,6 +628,7 @@ <module>commons-numbers-combinatorics</module> <module>commons-numbers-arrays</module> <module>commons-numbers-field</module> + <module>commons-numbers-rootfinder</module> </modules> </project>