Repository navigation
Expand file tree
/
Copy pathtest_gradient_descent_simple.c
More file actions
81 lines (67 loc) · 2.17 KB
/
Copy pathtest_gradient_descent_simple.c
File metadata and controls
81 lines (67 loc) · 2.17 KB
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
/**
* @file test_gradient_descent_simple.c
* @brief 简单测试梯度下降算法
*/
#include "cal_gradient_descent.h"
#include <stdio.h>
#include <math.h>
/**
* @brief 简单二次函数 f(x) = x^2
*/
cal_real_t simple_quadratic(const cal_real_t* x, uint32_t n, void* user_data) {
(void)user_data;
if (n != 1) return 0.0;
return x[0] * x[0];
}
/**
* @brief 梯度 f'(x) = 2x
*/
void simple_quadratic_gradient(const cal_real_t* x, uint32_t n, cal_real_t* gradient, void* user_data) {
(void)user_data;
if (n != 1 || gradient == NULL) return;
gradient[0] = 2.0f * x[0];
}
int main(void) {
printf("测试梯度下降算法\n");
printf("==================\n\n");
// 配置参数
cal_gd_config_t config;
cal_gradient_descent_default_config(&config);
config.initial_step_size = 0.1f;
config.tolerance = 1e-6f;
config.max_iterations = 100;
config.step_strategy = CAL_GD_STEP_FIXED;
// 初始化优化器
cal_gd_t gd;
cal_error_t err = cal_gradient_descent_init(
&gd, &config, simple_quadratic, simple_quadratic_gradient, 1, NULL
);
if (err != CAL_OK) {
printf("初始化失败,错误码:%d\n", err);
return 1;
}
// 初始点
cal_real_t x0[1] = {10.0f};
printf("目标函数:f(x) = x^2\n");
printf("初始点:x0 = %.2f\n", x0[0]);
printf("理论最优解:x* = 0.0, f* = 0.0\n\n");
// 执行优化
cal_gd_result_t result;
err = cal_gradient_descent_optimize(&gd, x0, &result);
// 输出结果
printf("优化结果:\n");
printf(" 状态:%s\n", err == CAL_OK ? "收敛" : "未收敛");
printf(" 迭代次数:%u\n", result.iterations);
printf(" 最优解:x* = %.10f\n", result.x_optimal[0]);
printf(" 最优值:f* = %.10f\n", result.f_optimal);
printf(" 梯度范数:%.10f\n", result.gradient_norm);
// 验证结果
if (fabs(result.x_optimal[0]) < 1e-5 && fabs(result.f_optimal) < 1e-10) {
printf("\n✓ 测试通过!\n");
} else {
printf("\n✗ 测试失败!\n");
}
// 释放资源
cal_gradient_descent_free(&gd);
return 0;
}