ellipse.py

Created by vnap0v

Created on June 04, 2025

1.12 KB

There is no closed-form expression for the circumference of an ellipse. This script approximates the circumference using the sum of a series. Height and width can be given, the ellipse is also plotted. Uses math and matplotlib. Tested on the calculator using software version 23.2.6.


from math import *
import matplotlib.pyplot as plt

# Binomial coefficient
def binomial(n,k):
  return factorial(n)/factorial(k)/factorial(n-k)

# circumference approx. by series
def circumference(a,b,nterms=6):
  h=(a-b)**2/(a+b)**2
  series=0
  for n in range(nterms):
    bin=binomial(2*n,n)
    denom=(2*n-1)*4**n
    series+=(bin/denom)**2 * h**n
  return pi*(a+b)*series

# surface area
def area(a,b):
  return pi*a*b

# plot using matplotlib
def plot_ellipse(a,b,cir,area):
  N=100
  x=[0.0]*N;y=[0.0]*N
  for k in range(100):
    angle=2*pi*k/99
    x[k]=a*cos(angle)
    y[k]=b*sin(angle)
  plt.plot(x,y)
  plt.grid()
  plt.text(-a*0.8,b*0.6,"Ellipse a={0} b={1}".format(a,b))
  plt.text(-a*0.8,b*0.4,"Circumference = {0:f}".format(cir))
  plt.text(-a*0.8,b*0.2,"Area = Area = {0:f}".format(area))
  plt.show()

def main():
  print("Circumference of ellipse")
  a=float(input("Height of ellipse? "))/2
  b=float(input("Width of ellipse? "))/2
  cir=circumference(a,b)
  s=area(a,b)
  print("Circumference={0:f}".format(cir))
  print("Area={0:f}".format(s))
  input("Hit <Exe> for plot")
  plot_ellipse(a,b,cir,s)

main()

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.