开发者

area and perimeter calculation of various shapes

Area of a circle, rectangle, triangle, trapezoid, parallelogram, ellipse, sector.
Perimeter of a rectangle, square

Is there a java library which provides mathematica开发者_Python百科l functions to calculate the above?


public double areaOfRectangle(double width, double length) {
  return width*height;
}
public double areaOfCircle(double radius) {
  return Math.PI * radius * radius;
}
public double areaOfTriangle(double a, double b, double c) {
  double s = (a+b+c)/2;
  return Math.sqrt(s * (s-a) * (s-b) * (s-c));
}

etc.

How hard can it be to code up yourself? Do you really need a library to do it for you?

You could also port this C code which implements area and perimeter calculations for many shapes.


I would not recommend that you use a library for such a thing. Just look up the formulas for each one and write the single line of code that each requires.

Sounds like somebody's classic first object-oriented assignment:

package geometry;

public interface Shape
{
    double perimeter();
    double area();
}

class Rectangle implements Shape
{
    private double width;
    private double height;

    Rectangle(double w, double h)
    {
        this.width = w;
        this.height = h;
    }

    public double perimeter()
    { 
        return 2.0*(this.width + this.height);
    }

    public double area()
    { 
        return this.width*this.height;
    }
}

// You get the idea - same for Triangle, Circle, Square with formula changes.


The only non trivial formula you asked for is the perimeter of an ellipse.

You'll need either complete elliptical integrals (google for that), or numerical integration, or approximate formulas (basically, the "Infinite Series 2" is the one you should use)


For the general case you could get an close estimate with a Monte Carlo method. You need a good random number generator. Take a rectangle large enough to contain the Shape and get a large number of random points in the rectangle. For each, use contains(double x, double y) to see if the point is in the Shape or not. The ratio of points in the Shape to all points in the rectangle, times the area of the rectangle is an estimate of the Shape area.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜