c# MathNet.Numerics 圆拟合使用案例

下载地址

https://www.nuget.org/packages/MathNet.Numerics/4.15.0#supportedframeworks-body-tab

原理

从标准圆方程(x-c1)2+(y-c2)2=r2中进行方程变换得到2xc1+2yc2+(r2−c12−c22)=x2+y2,其中,我们c3替换常量值r2−c12−c22,即:r2−c12−c22=c3。由此,我们得到2xc1+2yc2+c3=x2+y2,将点集带入,方程就只剩三个未知数`c1,c2 和 c3。

案例

csharp 复制代码
using MathNet.Numerics;
using MathNet.Numerics.LinearAlgebra.Double;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MathNetTest
{
    class Program
    {
        static void Main(string[] args)
        {
            FitCircle();
        }

        private static void FitCircle()
        {
            var count = 5000;
            var step = 2 * Math.PI / 100;
            var rd = new Random();
            //参照圆
            var x0 = 204.1;
            var y0 = 213.1;
            var r0 = 98.4;
            //噪音绝对差
            var diff = (int)(r0 * 0.1);
            var x = new double[count];
            var y = new double[count];
            //输出点集
            for (int i = 0; i < count; i++)
            {
                //circle
                x[i] = x0 + Math.Cos(i * step) * r0;
                y[i] = y0 + Math.Sin(i * step) * r0;
                //noise
                x[i] += Math.Cos(rd.Next() % 2 * Math.PI) * rd.Next(diff);
                y[i] += Math.Cos(rd.Next() % 2 * Math.PI) * rd.Next(diff);
            }

            var d = LinearAlgebraFit(x, y);


        }


        public static Tuple<double,double,double> LinearAlgebraFit(double[] X, double[] Y)
        {
            if (X.Length < 3)
            {
                return null;
            }
            var count = X.Length;
            var a = new double[count, 3];
            var c = new double[count, 1];
            for (int i = 0; i < count; i++)
            {
                //matrix
                a[i, 0] = 2 * X[i];
                a[i, 1] = 2 * Y[i];
                a[i, 2] = 1;
                c[i, 0] = X[i] * X[i] + Y[i] * Y[i];
            }
            var A = DenseMatrix.OfArray(a);
            var C = DenseMatrix.OfArray(c);
            //A*B=C
            var B = A.Solve(C);
            double c1 = B.At(0, 0),
                c2 = B.At(1, 0),
                r = Math.Sqrt(B.At(2, 0) + c1 * c1 + c2 * c2);
            Tuple<double, double, double> XYR = new Tuple<double, double, double>(c1, c2, r);
            return XYR;
        }
}
相关推荐
止观止8 分钟前
JavaScript对象创建9大核心技术解析
开发语言·javascript·ecmascript
screenCui1 小时前
macOS运行python程序遇libiomp5.dylib库冲突错误解决方案
开发语言·python·macos
linux kernel2 小时前
第七讲:C++中的string类
开发语言·c++
玩代码2 小时前
Java线程池原理概述
java·开发语言·线程池
水果里面有苹果2 小时前
20-C#构造函数--虚方法
java·前端·c#
泰勒疯狂展开2 小时前
Java研学-MongoDB(三)
java·开发语言·mongodb
zzywxc7872 小时前
AI技术通过提示词工程(Prompt Engineering)正在深度重塑职场生态和行业格局,这种变革不仅体现在效率提升,更在重构人机协作模式。
java·大数据·开发语言·人工智能·spring·重构·prompt
高hongyuan2 小时前
Go语言教程-占位符及演示代码
开发语言·后端·golang
她说人狗殊途3 小时前
多线程 JAVA
java·开发语言
星竹晨L3 小时前
C语言——预处理详解
c语言·开发语言