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 */ 017package org.apache.commons.math3.analysis.differentiation; 018 019import org.apache.commons.math3.analysis.MultivariateVectorFunction; 020 021/** Class representing the gradient of a multivariate function. 022 * <p> 023 * The vectorial components of the function represent the derivatives 024 * with respect to each function parameters. 025 * </p> 026 * @since 3.1 027 */ 028public class GradientFunction implements MultivariateVectorFunction { 029 030 /** Underlying real-valued function. */ 031 private final MultivariateDifferentiableFunction f; 032 033 /** Simple constructor. 034 * @param f underlying real-valued function 035 */ 036 public GradientFunction(final MultivariateDifferentiableFunction f) { 037 this.f = f; 038 } 039 040 /** {@inheritDoc} */ 041 public double[] value(double[] point) { 042 043 // set up parameters 044 final DerivativeStructure[] dsX = new DerivativeStructure[point.length]; 045 for (int i = 0; i < point.length; ++i) { 046 dsX[i] = new DerivativeStructure(point.length, 1, i, point[i]); 047 } 048 049 // compute the derivatives 050 final DerivativeStructure dsY = f.value(dsX); 051 052 // extract the gradient 053 final double[] y = new double[point.length]; 054 final int[] orders = new int[point.length]; 055 for (int i = 0; i < point.length; ++i) { 056 orders[i] = 1; 057 y[i] = dsY.getPartialDerivative(orders); 058 orders[i] = 0; 059 } 060 061 return y; 062 063 } 064 065}