実多項式の根

C言語によるサンプルソースコード : 使用関数名:nag_zeros_real_poly (c02agc)

Keyword: 実多項式の根

概要

本サンプルは実多項式の根を求めるC言語によるサンプルプログラムです。 本サンプルは以下に示される次数が5の多項式の根を求めて出力します。

実多項式の根のデータ 

※本サンプルはnAG Cライブラリに含まれる関数 nag_zeros_real_poly() のExampleコードです。本サンプル及び関数の詳細情報は nag_zeros_real_poly のマニュアルページをご参照ください。
ご相談やお問い合わせはこちらまで

入力データ

(本関数の詳細はnag_zeros_real_poly のマニュアルページを参照)
1
2
3

このデータをダウンロード
nag_zeros_real_poly (c02agc) Example Program Data
 5
     1.0    2.0    3.0    4.0    5.0    6.0

  • 1行目はタイトル行で読み飛ばされます。
  • 2行目に多項式の次数(n)を指定しています。
  • 3行目に各項の係数(a)を指定しています。

出力結果

(本関数の詳細はnag_zeros_real_poly のマニュアルページを参照)
1
2
3
4
5
6
7
8
9

この出力例をダウンロード
nag_zeros_real_poly (c02agc) Example Program Results

Degree of polynomial =    5

Roots of polynomial

z =   -1.4918e+00
z =    5.5169e-01   +/-     1.2533e+00
z =   -8.0579e-01   +/-     1.2229e+00

  • 3行目に入力された多項式の次数が出力されています。
  • 7から9行目に多項式の根(実部と虚部)が出力されています。

ソースコード

(本関数の詳細はnag_zeros_real_poly のマニュアルページを参照)

※本サンプルソースコードはnAG数値計算ライブラリ(Windows, Linux, MAC等に対応)の関数を呼び出します。
サンプルのコンパイル及び実行方法

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

このソースコードをダウンロード
/* nag_zeros_real_poly (c02agc) Example Program.
 *
 * CLL6I261D/CLL6I261DL Version.
 *
 * Copyright 2017 Numerical Algorithms Group.
 *
 * Mark 26.1, 2017.
 *
 */

#include <nag.h>
#include <stdio.h>
#include <math.h>
#include <nag_stdlib.h>
#include <nagc02.h>

int main(void)
{

  Nag_Boolean scale;
  Complex *z = 0;
  Integer exit_status = 0, i, n, nroot;
  NagError fail;
  double *a = 0;

  INIT_FAIL(fail);

  printf("nag_zeros_real_poly (c02agc) Example Program Results\n");
  /* Skip heading in data file */
  scanf("%*[^\n]");
  scanf("%ld", &n);
  if (n > 0) {
    scale = Nag_TRUE;
    if (!(a = nAG_ALLOC(n + 1, double)) || !(z = nAG_ALLOC(n, Complex)))
    {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }
  }
  else {
    printf("Invalid n.\n");
    exit_status = 1;
    return exit_status;
  }

  for (i = 0; i <= n; i++)
    scanf("%lf", &a[i]);
  printf("\nDegree of polynomial = %4ld\n\n", n);

  /* nag_zeros_real_poly (c02agc).
   * Zeros of a polynomial with real coefficients
   */
  nag_zeros_real_poly(n, a, scale, z, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_zeros_real_poly (c02agc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }

  printf("Roots of polynomial\n\n");
  nroot = 1;
  while (nroot <= n) {
    if (z[nroot - 1].im == 0.0) {
      printf("z = %13.4e\n", z[nroot - 1].re);
      nroot += 1;
    }
    else {
      printf("z = %13.4e   +/- %14.4e\n", z[nroot - 1].re,
             fabs(z[nroot - 1].im));
      nroot += 2;
    }
  }
END:
  nAG_FREE(a);
  nAG_FREE(z);
  return exit_status;
}


関連情報
© 日本ニューメリカルアルゴリズムズグループ株式会社 2025
Privacy Policy  /  Trademarks