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.math3.analysis.differentiation; 018 019 import 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 * @version $Id: GradientFunction.java 1416643 2012-12-03 19:37:14Z tn $ 027 * @since 3.1 028 */ 029 public class GradientFunction implements MultivariateVectorFunction { 030 031 /** Underlying real-valued function. */ 032 private final MultivariateDifferentiableFunction f; 033 034 /** Simple constructor. 035 * @param f underlying real-valued function 036 */ 037 public GradientFunction(final MultivariateDifferentiableFunction f) { 038 this.f = f; 039 } 040 041 /** {@inheritDoc} */ 042 public double[] value(double[] point) 043 throws IllegalArgumentException { 044 045 // set up parameters 046 final DerivativeStructure[] dsX = new DerivativeStructure[point.length]; 047 for (int i = 0; i < point.length; ++i) { 048 dsX[i] = new DerivativeStructure(point.length, 1, i, point[i]); 049 } 050 051 // compute the derivatives 052 final DerivativeStructure dsY = f.value(dsX); 053 054 // extract the gradient 055 final double[] y = new double[point.length]; 056 final int[] orders = new int[point.length]; 057 for (int i = 0; i < point.length; ++i) { 058 orders[i] = 1; 059 y[i] = dsY.getPartialDerivative(orders); 060 orders[i] = 0; 061 } 062 063 return y; 064 065 } 066 067 }