0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

参考文献

数値計算法(第2版)
千葉工業大学名誉教授 工学博士 三井田 惇郎 (共著)
千葉工業大学准教授 博士(工学) 須田 宇宙 (共著)
発売日 1991/4/14

準備

オンラインコンパイラを使用します。

ソースコード

sample.c
#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <math.h>
#include <time.h>

// 非線形関数の定義
double nonlinear_function(double x) {
    return x * x - 4 * x + 4;
}

// モンテカルロ法による最適化
void monte_carlo_optimization(int iterations, double *best_solution, double *best_value) {
    *best_solution = 0.0;
    *best_value = DBL_MAX;
    
    for (int i = 0; i < iterations; i++) {
        // ランダムな値を生成
        double x = ((double)rand() / RAND_MAX) * 20.0 - 10.0;
        double y = nonlinear_function(x);
        
        // より良い解が見つかった場合、更新
        if (y < *best_value) {
            *best_solution = x;
            *best_value = y;
        }
    }
}

int main() {
    srand(time(0));
    
    double best_solution, best_value;
    monte_carlo_optimization(10000, &best_solution, &best_value);
    
    printf("最適解: x = %f\n", best_solution);
    printf("最小値: f(x) = %f\n", best_value);
    
    return 0;
}

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?