001 /*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.commons.nabla.numerical;
018
019 import org.apache.commons.nabla.core.DifferentialPair;
020 import org.apache.commons.nabla.core.UnivariateDerivative;
021 import org.apache.commons.nabla.core.UnivariateDifferentiable;
022
023 /** Two-points finite differences scheme.
024 * The error model for the two-points scheme is
025 * <code>h<sup>2</sup>/6 f<sup>(3)</sup>(x) + O(h<sup>4</sup>)</code>.
026 */
027 public class TwoPointsScheme extends FiniteDifferencesDifferentiator {
028
029 /** Serializable UID. */
030 private static final long serialVersionUID = -5824475098109485044L;
031
032 /** Scheme denominator. */
033 private final double denominator;
034
035 /** Build a 2-points finite differences scheme.
036 * @param h differences step size
037 */
038 public TwoPointsScheme(final double h) {
039 super(h, h * h / 6, 3);
040 denominator = 2 * h;
041 }
042
043 /** {@inheritDoc} */
044 public UnivariateDerivative differentiate(final UnivariateDifferentiable d) {
045 return new UnivariateDerivative() {
046
047 /** {@inheritDoc} */
048 public UnivariateDifferentiable getPrimitive() {
049 return d;
050 }
051
052 /** {@inheritDoc} */
053 public DifferentialPair f(final DifferentialPair t) {
054 final double h = getStepSize();
055 final double u0 = t.getValue();
056 final double ft = d.f(u0);
057 final double d1 = d.f(u0 + h) - d.f(u0 - h);
058 return new DifferentialPair(ft, t.getFirstDerivative() * d1 / denominator);
059 }
060
061 };
062 }
063
064 }