■ Hill Climbing 알고리즘을 사용해 최적해를 구하는 방법을 보여준다.
▶ Program.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
namespace TestProject; public class Program { //////////////////////////////////////////////////////////////////////////////////////////////////// Method ////////////////////////////////////////////////////////////////////////////////////////// Static //////////////////////////////////////////////////////////////////////////////// Private #region 목표 함수 처리하기 - ObjectiveFunction(x) /// <summary> /// 목표 함수 처리하기 /// </summary> /// <param name="x">X 인자</param> /// <returns>목표 함수</returns> private static double ObjectiveFunction(double x) { return -(x * x) + 5 * x + 10; // 예 : f(x) = -x^2 + 5x + 10 } #endregion #region 최적화하기 - Optimize(start, stepSize, maximumIterationCount) /// <summary> /// 최적화하기 /// </summary> /// <remarks>Hill Climbing 알고리즘을 사용한다.</remarks> /// <param name="start">시작</param> /// <param name="stepSize">단계 크기</param> /// <param name="maximumIterationCount">최대 반복 수</param> /// <returns>최적해</returns> private static double Optimize(double start, double stepSize, int maximumIterationCount) { double currentX = start; double currentValue = ObjectiveFunction(currentX); for(int i = 0; i < maximumIterationCount; i++) { double leftX = currentX - stepSize; double rightX = currentX + stepSize; double leftValue = ObjectiveFunction(leftX); double rightValue = ObjectiveFunction(rightX); if(leftValue > currentValue && leftValue > rightValue) { currentX = leftX; currentValue = leftValue; } else if(rightValue > currentValue) { currentX = rightX; currentValue = rightValue; } else { break; } } return currentX; } #endregion #region 프로그램 시작하기 - Main() /// <summary> /// 프로그램 시작하기 /// </summary> private static void Main() { double startX = 0; double stepSize = 0.1; int maximumIterationCount = 100; double result = Optimize(startX, stepSize, maximumIterationCount); Console.WriteLine($"최적해 : x = {result}, f(x) = {ObjectiveFunction(result)}"); } #endregion } |