Utilities.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include <NumericalMethods/Optimization.h>
  9. #include <Optimization/Constants.h>
  10. #include <Optimization/Utilities.h>
  11. namespace NumericalMethods::Optimization
  12. {
  13. double FunctionValue(const Function& function, const VectorVariable& point)
  14. {
  15. return function.Execute(point.GetValues()).GetValue();
  16. }
  17. double DirectionalDerivative(const Function& function, const VectorVariable& point, const VectorVariable& direction)
  18. {
  19. return Gradient(function, point).Dot(direction);
  20. }
  21. VectorVariable Gradient(const Function& function, const VectorVariable& point)
  22. {
  23. const AZ::u32 dimension = point.GetDimension();
  24. VectorVariable gradient(dimension);
  25. VectorVariable direction(dimension);
  26. for (AZ::u32 i = 0; i < dimension; i++)
  27. {
  28. direction[i] = 1.0;
  29. double f_plus = FunctionValue(function, point + epsilon * direction);
  30. double f_minus = FunctionValue(function, point - epsilon * direction);
  31. gradient[i] = (f_plus - f_minus) / (2.0 * epsilon);
  32. direction[i] = 0.0;
  33. }
  34. return gradient;
  35. }
  36. } // namespace NumericalMethods::Optimization