LoginSignup
0
2

More than 3 years have passed since last update.

ニュートン法で平方根を求める

Last updated at Posted at 2018-10-12

はじめに

今回はニュートン法で平方根を求めていきたいと思います。

簡単に実装

Source.cpp
#include <iostream>

namespace sqn {

    inline const double func(const double x_, const double num_) { return x_ * x_ - num_; }
    inline const double func2(const double x_) { return 2 * x_; }
    const bool abs_eps(double num_) {
        constexpr double EPS{ 0.0001 };
        if (num_ < 0.0) num_ *= -1;
        return (num_ < EPS);
    }
    //平方根を求める
    double sqrtn(double num_) {
        double a{ 1.0 };
        const double c{ num_ };
        int i{};
        while (true) {
            num_ = a - func(a, c) / func2(a);
            std::cout << i << "回目: x = " << num_ << std::endl;
            if (abs_eps(a - num_)) break;
            else a = num_;
            ++i;
        }
        return num_;
    }
}

//メイン関数
int main() {
    //平方根を求める
    sqn::sqrtn(256.0);
    return 0;
}



出力結果
0回目: x = 128.5
1回目: x = 65.2461
2回目: x = 34.5849
3回目: x = 20.9935
4回目: x = 16.5939
5回目: x = 16.0106
6回目: x = 16
7回目: x = 16

ニュートン法のループ回数と途中経過の値を出力します。

ライブラリとして実装

Sqrtn.hpp
namespace sqn {
    inline const double func(const double x_, const double num_) { return x_ * x_ - num_; }
    inline const double func2(const double x_) { return 2 * x_; }
    const bool abs_eps(double num_) {
        constexpr double EPS{ 0.0001 };
        if (num_ < 0.0) num_ *= -1.0;
        return (num_ < EPS);
    }
    double sqrtn(double num_) {
        double a{ 1.0 };
        const double c{ num_ };
        while (true) {
            num_ = a - func(a, c) / func2(a);
            if (abs_eps(a - num_)) break;
            else a = num_;
        }
        return num_;
    }
}
Source.cpp
#include <iostream>
#include "Sqrtn.hpp"

//メイン関数
int main() {
    //平方根を求める
    std::cout << sqn::sqrtn(256.0) << std::endl;
    return 0;
}
出力結果
16

平方根の値を出せました。

ソースコードのライセンス

These codes are licensed under CC0.
CC0

ソースコードは自由に使用してください。

0
2
1

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
2