Added "derivative".

git-svn-id: https://svn.apache.org/repos/asf/commons/proper/math/trunk@1183776 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
Gilles Sadowski 2011-10-16 00:51:42 +00:00
parent 2d9e88f2d6
commit f258ecdf91
2 changed files with 68 additions and 1 deletions

View File

@ -18,6 +18,7 @@
package org.apache.commons.math.analysis.function;
import org.apache.commons.math.analysis.UnivariateRealFunction;
import org.apache.commons.math.analysis.DifferentiableUnivariateRealFunction;
import org.apache.commons.math.util.FastMath;
/**
@ -26,9 +27,19 @@ import org.apache.commons.math.util.FastMath;
* @version $Id$
* @since 3.0
*/
public class Sqrt implements UnivariateRealFunction {
public class Sqrt implements DifferentiableUnivariateRealFunction {
/** {@inheritDoc} */
public double value(double x) {
return FastMath.sqrt(x);
}
/** {@inheritDoc} */
public UnivariateRealFunction derivative() {
return new UnivariateRealFunction() {
/** {@inheritDoc} */
public double value(double x) {
return 1 / (2 * FastMath.sqrt(x));
}
};
}
}

View File

@ -0,0 +1,56 @@
/*
* 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.math.analysis.function;
import org.apache.commons.math.analysis.UnivariateRealFunction;
import org.junit.Test;
import org.junit.Assert;
public class SqrtTest {
@Test
public void testComparison() {
final Sqrt s = new Sqrt();
final UnivariateRealFunction f = new UnivariateRealFunction() {
public double value(double x) {
return Math.sqrt(x);
}
};
for (double x = 1e-30; x < 1e10; x *= 2) {
final double fX = f.value(x);
final double sX = s.value(x);
Assert.assertEquals("x=" + x, fX, sX, 0);
}
}
@Test
public void testDerivativeComparison() {
final UnivariateRealFunction sPrime = (new Sqrt()).derivative();
final UnivariateRealFunction f = new UnivariateRealFunction() {
public double value(double x) {
return 1 / (2 * Math.sqrt(x));
}
};
for (double x = 1e-30; x < 1e10; x *= 2) {
final double fX = f.value(x);
final double sX = sPrime.value(x);
Assert.assertEquals("x=" + x, fX, sX, 0);
}
}
}