Skip to content
This repository has been archived by the owner on Dec 21, 2023. It is now read-only.

Commit

Permalink
feat(core.py): add ackley
Browse files Browse the repository at this point in the history
  • Loading branch information
estripling committed Aug 21, 2022
1 parent ed87fec commit d7804e2
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
45 changes: 45 additions & 0 deletions src/fbench/core.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,51 @@
import numpy as np


def ackley(x):
"""Ackley function.
.. math::
f(\\mathbf{x}) =
-20 \\exp \\left(
-0.2 \\sqrt{ \\frac{1}{n} \\sum_{i=1}^n x_i^2 }
\\right)
- \\exp \\left( \\frac{1}{n} \\sum_{i=1}^n \\cos(2 \\pi x_i) \\right)
+ 20
+ e
Parameters
----------
x : array_like
A real-valued vector to evaluate.
Returns
-------
float
Function value at x.
References
----------
.. [1] "Test functions for optimization", Wikipedia,
`<https://en.wikipedia.org/wiki/Test_functions_for_optimization>`_
Examples
--------
>>> round(ackley([0, 0]), 4)
0.0
>>> round(ackley([1, 1]), 4)
3.6254
"""
x = np.asarray(x)
return float(
-20 * np.exp(-0.2 * np.sqrt((x**2).mean()))
- np.exp((np.cos(2 * np.pi * x)).sum() / len(x))
+ 20
+ np.e
)


def sphere(x):
"""Sphere function.
Expand Down
14 changes: 14 additions & 0 deletions tests/test_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,20 @@
from fbench import core


@pytest.mark.parametrize(
"arg, expected",
[
([0], 0.0),
([0, 0], 0.0),
([1, 1], 3.6254),
([2, 2], 6.5936),
],
)
def test_ackley(arg, expected):
actual = core.ackley(x=arg)
assert round(actual, 4) == expected


@pytest.mark.parametrize(
"arg, expected",
[
Expand Down

0 comments on commit d7804e2

Please sign in to comment.