Last active
April 18, 2016 16:56
-
-
Save shannonwells/addd4eade8bb62680bdc to your computer and use it in GitHub Desktop.
A Sphere class that can give you random, uniformly distributed coordinates on the surface of a sphere. Default creates a unit sphere. You can set the sphere's radius directly or set it by its known volume ("Assume a spherical cow...")
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# https://www.jasondavies.com/maps/random-points/ | |
require 'rspec' | |
require 'awesome_print' | |
class Sphere | |
attr_accessor :radius, :units | |
def initialize(radius=1.0) | |
srand | |
@radius = radius*1.0 | |
end | |
# We want φ ∈ [-90°, 90°) | |
# φ = cos^(-1)(2x - 1), where x is uniformly distributed and x ∈ [0, 1) | |
def random_phi(units = :radians) | |
raise StandardError.new("only #{self.class.allowed_angular_units} allowed.") unless self.class.allowed_angular_units.include? units | |
x = rand | |
# acos returns [ 0 - π ) | |
rads = Math.acos(2*x - 1) - Math::PI/2 | |
return rads if units == :radians | |
return rads*180/Math::PI | |
end | |
# pick λ ∈ [-180°, 180°) | |
def random_theta(units = :radians) | |
degrees = rand*360 - 180 | |
raise StandardError.new("only #{self.class.allowed_angular_units} allowed.") unless self.class.allowed_angular_units.include? units | |
return degrees if units == :degrees | |
return degrees*Math::PI/180 | |
end | |
def random_latitude | |
random_phi(:degrees) | |
end | |
def random_longitude | |
random_theta(:degrees) + 360 | |
end | |
def volume | |
Math::PI*radius*radius*radius | |
end | |
def area | |
4*Math::PI*radius*radius | |
end | |
# takes the new volume and sets the radius. | |
def volume=(new_volume) | |
float_vol = new_volume * 1.0 | |
self.radius = Math.cbrt(float_vol/Math::PI) | |
end | |
private | |
def self.allowed_angular_units | |
[:radians, :degrees] | |
end | |
end |
Author
shannonwells
commented
Jan 29, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment