Skip to content

Instantly share code, notes, and snippets.

@wipiano
Created August 13, 2017 09:36
Show Gist options
  • Save wipiano/c52740d3f2ace1322de62861f48ea6d5 to your computer and use it in GitHub Desktop.
Save wipiano/c52740d3f2ace1322de62861f48ea6d5 to your computer and use it in GitHub Desktop.
ニュートン法
using System;
namespace AppliedITEnginnerMisc
{
/// <summary>
/// ニュートン法の実装
/// </summary>
public sealed class Newton
{
/// <summary>
/// f(x)
/// </summary>
private readonly Func<double, double> _func;
/// <summary>
/// f'(x)
/// </summary>
private readonly Func<double, double> _differentiated;
/// <summary>
/// 収束判定値
/// </summary>
public double E { get; set; }
/// <summary>
/// constructor
/// </summary>
/// <param name="func">非線形方程式 f(x) = 0 の左辺</param>
/// <param name="differentiated">f(x) の微分</param>
public Newton(Func<double, double> func, Func<double, double> differentiated)
{
_func = func;
_differentiated = differentiated;
}
/// <summary>
/// ニュートン法により非線形方程式 func(x) = 0 の実根の近似値を求めます
/// </summary>
/// <param name="initial">初期値</param>
/// <returns>近似値</returns>
public double Calc(double initial)
{
// x1 = x0 - (f(x0) / f'(x0))
double x0;
double x1 = initial;
do
{
x0 = x1;
x1 = (x0 - (_func(x0) / _differentiated(x0)));
} while ((Math.Abs(x0 - x1)) >= this.E);
return x1;
}
}
}
using AppliedITEnginnerMisc;
using Xunit;
using Xunit.Abstractions;
namespace Tests
{
public class NewtonTest
{
private readonly ITestOutputHelper _output;
public NewtonTest(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void Test1()
{
// x^2 - 16 = 0 のひとつの実根をもとめてみる
// f(x) = x^2 - N
// f'(x) = 2x
var newton = new Newton(x => x * x - 16, x => 2 * x)
{
E = 1
};
_output.WriteLine(newton.Calc(3).ToString());
newton.E = 0.0001;
_output.WriteLine(newton.Calc(3).ToString());
newton.E = 0.0000001;
_output.WriteLine(newton.Calc(6).ToString());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment