鞋带配方的最快方法 [英] Fastest way to Shoelace formula
本文介绍了鞋带配方的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我做了一个函数,可以用鞋带方式计算面积多边形.
I have made a function who calculate area polygon with Shoelace way.
这很完美,但是现在我想知道是否没有更快的方法来获得相同的结果. 我想知道,因为此功能必须在具有很多坐标的多边形上更快地工作.
That's works perfectly but right now I wonder if there is not a faster way to have the same result. I want to know that because this function must work faster with polygon with a lot of coordinates.
我的功能:
def shoelace_formula(polygonBoundary, absoluteValue = True):
nbCoordinates = len(polygonBoundary)
nbSegment = nbCoordinates - 1
l = [(polygonBoundary[i+1][0] - polygonBoundary[i][0]) * (polygonBoundary[i+1][1] + polygonBoundary[i][1]) for i in xrange(nbSegment)]
if absoluteValue:
return abs(sum(l) / 2.)
else:
return sum(l) / 2.
我的多边形:
polygonBoundary = ((5, 0), (6, 4), (4, 5), (1, 5), (1, 0))
结果:
22.
有什么想法吗?
我尝试Numpy: 这是最快的方法,但您必须先转换坐标.
I try with Numpy : It's speedest but you have to convert your coordinates first.
import numpy as np
x, y = zip(*polygonBoundary)
def shoelace_formula_3(x, y, absoluteValue = True):
result = 0.5 * np.array(np.dot(x, np.roll(y, 1)) - np.dot(y, np.roll(x, 1)))
if absoluteValue:
return abs(result)
else:
return result
推荐答案
class Point //a new class for an any point a(X,Y), b(X,Y), c(X,Y), d(X,Y)
{
//private int x, y;
public int X { get; set; }
public int Y { get; set; }
}
static class Geometry
{
public static void GerArea(Point a, Point b, Point c)
{
double area = 0.5 * ( (a.X * b.Y) + (b.X * c.Y) + (c.X * a.Y) - (b.X * a.Y) - (c.X * b.Y) - (a.X * c.Y) );
Console.WriteLine(Math.Abs(area));
}
public static void GerArea(Point a, Point b, Point c, Point d)
{
double area = 0.5 * ((a.X * b.Y) + (b.X * c.Y) + (c.X * d.Y) + (d.X * a.Y) - (b.X * a.Y) - (c.X * b.Y) - (d.X * c.Y) - (a.X * d.Y ) );
Console.WriteLine(Math.Abs(area));
}
}
class Program
{
static void Main(string[] args)
{
Point a = new Point() { X = -12, Y = 12 };
Point b = new Point() { X = 15, Y = 15 };
Point c = new Point() { X = -15, Y = -16 };
Point d = new Point() { X = 16, Y = -15 };
Console.WriteLine("****Shoelace formula****\n");
Console.Write("Area of tringle: ");
Geometry.GerArea(a, b, c);
Console.Write("Area of quad: ");
Geometry.GerArea(a, b, c, d);
Console.ReadLine();
}
}
这篇关于鞋带配方的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文