Jason
Jason

Reputation: 12789

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 mathematical functions to calculate the above?

Upvotes: 0

Views: 17050

Answers (4)

Larry H
Larry H

Reputation: 1

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.

Upvotes: -1

moinudin
moinudin

Reputation: 138507

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.

Upvotes: 4

Alexandre C.
Alexandre C.

Reputation: 56996

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)

Upvotes: 1

duffymo
duffymo

Reputation: 309018

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.

Upvotes: 2

Related Questions