1 Star 0 Fork 63

雁秋 / C-Sharp

forked from 编程语言算法集 / C-Sharp 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
Manhattan.cs 1.27 KB
一键复制 编辑 原始数据 按行查看 历史
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Algorithms.LinearAlgebra.Distances
{
/// <summary>
/// Implementation fo Manhattan distance.
/// It is the sum of the lengths of the projections of the line segment between the points onto the coordinate axes.
/// In other words, it is the sum of absolute difference between the measures in all dimensions of two points.
///
/// Its commonly used in regression analysis.
/// </summary>
public static class Manhattan
{
/// <summary>
/// Calculate Manhattan distance for two N-Dimensional points.
/// </summary>
/// <param name="point1">First N-Dimensional point.</param>
/// <param name="point2">Second N-Dimensional point.</param>
/// <returns>Calculated Manhattan distance.</returns>
public static double Distance(double[] point1, double[] point2)
{
if (point1.Length != point2.Length)
{
throw new ArgumentException("Both points should have the same dimensionality");
}
// distance = |x1-y1| + |x2-y2| + ... + |xn-yn|
return point1.Zip(point2, (x1, x2) => Math.Abs(x1 - x2)).Sum();
}
}
}
C#
1
https://gitee.com/xyesterday/C-Sharp.git
git@gitee.com:xyesterday/C-Sharp.git
xyesterday
C-Sharp
C-Sharp
master

搜索帮助