fork download
  1. #include <stdio.h>
  2. #include <math.h>
  3.  
  4. #define SIZE 4
  5.  
  6. // ガウスの消去法で行列式を計算する関数
  7. double calculate_determinant(double lambda) {
  8. // 画像の行列 A - λI をセット
  9. // ※ A[1][1] の位置は「-5.0 - lambda」になります
  10. double mat[SIZE][SIZE] = {
  11. {1.0 - lambda, 2.0, 3.0, 5.0},
  12. {3.0, -5.0 - lambda, 1.0, 4.0},
  13. {5.0, 9.0, 2.0 - lambda, -6.0},
  14. {1.0, 7.0, 4.0, 1.0 - lambda}
  15. };
  16.  
  17. double det = 1.0;
  18.  
  19. for (int i = 0; i < SIZE; i++) {
  20. // ピボットが0に近い場合の処理(簡易的な部分ピボット選択)
  21. if (fabs(mat[i][i]) < 1e-9) {
  22. int swap_row = -1;
  23. for (int k = i + 1; k < SIZE; k++) {
  24. if (fabs(mat[k][i]) > 1e-9) {
  25. swap_row = k;
  26. break;
  27. }
  28. }
  29. if (swap_row == -1) return 0.0; // 行列式は0
  30.  
  31. // 行の入れ替え
  32. for (int j = 0; j < SIZE; j++) {
  33. double temp = mat[i][j];
  34. mat[i][j] = mat[swap_row][j];
  35. mat[swap_row][j] = temp;
  36. }
  37. det *= -1.0; // 行を入れ替えたので符号を反転
  38. }
  39.  
  40. // 下三角成分を消去
  41. for (int k = i + 1; k < SIZE; k++) {
  42. double factor = mat[k][i] / mat[i][i];
  43. for (int j = i; j < SIZE; j++) {
  44. mat[k][j] -= factor * mat[i][j];
  45. }
  46. }
  47. // 対角成分を掛け合わせる
  48. det *= mat[i][i];
  49. }
  50.  
  51. return det;
  52. }
  53.  
  54. int main() {
  55. printf("=== 特性方程式 det(A - λI) の係数確認用チェック ===\n");
  56.  
  57. // 特定の λ を代入して、多項式が 0 になるか(=固有値か)をテスト
  58. // あなたがべき乗法で見つけた「8.6120894541」をテストします
  59. double test_lambda = 8.6120894541;
  60. double result = calculate_determinant(test_lambda);
  61.  
  62. printf("λ = %.10f のときの行列式の値: %e\n", test_lambda, result);
  63.  
  64. if (fabs(result) < 1e-4) {
  65. printf("-> 行列式がほぼ0になったため、この値は間違いなく正しい固有値(根)です。\n");
  66. } else {
  67. printf("-> 0になりません。方程式か固有値のどちらかがズレています。\n");
  68. }
  69.  
  70. return 0;
  71. }
Success #stdin #stdout 0s 5308KB
stdin
Standard input is empty
stdout
=== 特性方程式 det(A - λI) の係数確認用チェック ===
λ = 8.6120894541 のときの行列式の値: -1.395376e+02
-> 0になりません。方程式か固有値のどちらかがズレています。