From 6bf42c2194d74c68f40cf993c0943f8343a9b58c Mon Sep 17 00:00:00 2001 From: leo Date: Sun, 5 Feb 2023 13:28:05 +0100 Subject: [PATCH] cec2020: implement Rastrigin func + test --- bench/cec2020/basicFunctions.go | 12 +++++++-- bench/cec2020/basicFunctions_test.go | 37 ++++++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 2 deletions(-) create mode 100644 bench/cec2020/basicFunctions_test.go diff --git a/bench/cec2020/basicFunctions.go b/bench/cec2020/basicFunctions.go index 98682bd..98b02bf 100644 --- a/bench/cec2020/basicFunctions.go +++ b/bench/cec2020/basicFunctions.go @@ -5,8 +5,16 @@ package cec2020 import "math" -// Rastrigin computes the value of the Rastrigin function for x. -func Rastrigin(x []float64) float64 { return 0 } +// Rastrigin calculates the value of the Rastrigin function for x. +func Rastrigin(x []float64) float64 { + var sum float64 + + for i := range x { + sum += math.Pow(x[i], 2) - (10 * math.Cos(2*math.Pi*x[i])) + 10 + } + + return sum +} // HighConditionedElliptic is the "High Conditioned Elliptic Function" of // CEC2020. diff --git a/bench/cec2020/basicFunctions_test.go b/bench/cec2020/basicFunctions_test.go new file mode 100644 index 0000000..f8bbddd --- /dev/null +++ b/bench/cec2020/basicFunctions_test.go @@ -0,0 +1,37 @@ +// Copyright 2023 wanderer +// SPDX-License-Identifier: GPL-3.0-or-later + +package cec2020 + +import "testing" + +// TestRastrigin checks that the Rastrigin func performs as expected. +func TestRastrigin(t *testing.T) { + testInput := []float64{ + -2.7137778065280593, + -1.9789783390895765, + -4.38267902085263, + -4.617877608383319, + -2.1529909200665474, + -3.801849324611571, + 2.4968697503272486, + -0.27358100201730196, + 2.0444319451255977, + 3.8798952350630653, + -0.6150024279011337, + 2.8643010641852413, + -0.6692444051928748, + 4.4649633199687475, + 3.2510298731558507, + -4.2095036422081495, + -0.130882052243404, + 1.2001716295708604, + -0.29427650577602193, + } + want := 343.97127081044846 + got := Rastrigin(testInput) + + if want != got { + t.Errorf("incorrect Rastrigin output, want: %f, got: %f", want, got) + } +}