# 1-15-Ruby.rb # # Ruby has a number of conventions that distinguish # it from C and C++. For example, parentheses are # often omitted when calling simple methods, and the # value of the final expression in a method is # automatically returned. # my_sin(x) # # Approximate sin(x) using the Taylor series # # x^3 x^5 x^7 # sin(x) = x - --- + --- - --- + ... # 3! 5! 7! # # Rather than calculating each power and factorial # separately, calculate each term from the previous # term: # # x^2 # next = -term ----------- # n(n + 1) # # where n takes the values 2, 4, 6, ... def my_sin(x) return Float::NAN unless x.finite? result = x term = x n = 2.0 loop do term *= -(x/n)*(x/(n + 1.0)) break if term.abs < 1e-16 result += term n += 2.0 end result end x = 3.2 puts "my_sin(x): #{my_sin(x)}" puts "Math.sin(x): #{Math.sin(x)}" puts "reference: #{-0.058374143427579909137}" # Ruby provides named floating-point values for # positive infinity and NaN. puts "my_sin(Float::INFINITY): #{my_sin(Float::INFINITY)}"