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 /** Four-points finite differences scheme.
024 * The error model for the four-points scheme is
025 * <code>-2h<sup>4</sup>/5 f<sup>(5)</sup>(x) + O(h<sup>6</sup>)</code>.
026 */
027 public class FourPointsScheme extends FiniteDifferencesDifferentiator {
028
029 /** Serializable UID. */
030 private static final long serialVersionUID = 3216911780962952859L;
031
032 /** Scheme denominator. */
033 private final double denominator;
034
035 /** Build a 4-points finite differences scheme.
036 * @param h differences step size
037 */
038 public FourPointsScheme(final double h) {
039 super(h, -2 * h * h * h * h / 5, 5);
040 denominator = 12 * 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 final double d2 = d.f(u0 + 2 * h) - d.f(u0 - 2 * h);
059 return new DifferentialPair(ft, t.getFirstDerivative() * (8 * d1 - d2) / denominator);
060 }
061
062 };
063 }
064
065 }