Skip to content

Instantly share code, notes, and snippets.

@jasondew
Created July 9, 2010 22:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jasondew/470191 to your computer and use it in GitHub Desktop.
Save jasondew/470191 to your computer and use it in GitHub Desktop.
require 'algebra'
class IRR
def self.calculate(profits)
begin
function(profits).zero
rescue Algebra::MaximumIterationsReached => mir
nil
end
end
private
def self.function(profits)
Algebra::Function.new do |x|
sumands = Array.new
profits.each_with_index {|profit, index| sumands << profit.to_f / (1 + x) ** index }
sumands.inject(0) {|sum, sumand| sum + sumand }
end
end
end
puts IRR.calculate([-100, 30, 35, 40, 45])
puts IRR.calculate([-1, 1])
puts IRR.calculate([])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment