Ruby Math.radians
I need Math.radians() function and canno开发者_如何学Got find it.
radians=(angle/180)* Math::PI
You probably want to create a file called "mymath.rb" in the lib/ directory, and monkey patch Math, like this:
require 'mathn'
module Math
def self.to_rad angle
angle / 180.0 * Math::PI
end
end
or you can do what @MBO said in his comment. The link seems to be down, but the Google archives yield this informative little sentence, which indicates a solution that may be cleaner than mine (though I prefer keeping math stuff inside of math):
The simplest solution is to define a conversion method in Numeric that will convert a number of degrees into radians.
As a note, Ruby 2.0 has a feature called "Refinement" that basically lets you do local monkey-patching. It works this way (lifted from this blog post :
module RadiansConversion
refine Math do
def to_rad angle
angle / 180.0 * Math::PI
end
end
end
And then .... It's available inside another module or anything such like that.
module MyApp
using RadiansConversion
p Math.to_rad 180 #=> 3.14159265358979
p Math.to_rad 235 #=> 4.10152374218667
end
Or you could extend Float to add a 'to_rad' convertion:
class Float
def to_rad
self/180 * Math::PI
end
end
And use it like this
radian=angle.to_rad
EDIT (because of down voting): Sorry! The time I answered, I needed this for an array of values and just wanted to share what I found.
So, yes actually it is just:
x * (Math::PI / 180)
Just wanted to show an implementation I found.
# Geocoder::Calculations.to_radians(@geocode)
def to_radians(*args)
args = args.first if args.first.is_a?(Array)
if args.size == 1
args.first * (Math::PI / 180)
else
args.map{ |i| to_radians(i) }
end
end
Convert degrees to radians. If an array (or multiple arguments) is passed, converts each value and returns array.
http://rubydoc.info/github/alexreisner/geocoder/master/Geocoder/Calculations#to_radians-instance_method
精彩评论