Advertisement
cd62131

sin cos

May 13th, 2018
266
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.05 KB | None | 0 0
  1. #!/usr/bin/env ruby
  2. def sincos(x, n)
  3.   if x < 0
  4.     s, c = sincos(-x, n)
  5.     return [-s + 0, c]
  6.   end
  7.   x -= 2 * Math::PI while x >= 2 * Math::PI
  8.   case x
  9.   when 0 .. Math::PI / 4
  10.     return sincos_sub(x, n)
  11.   when Math::PI / 4 .. Math::PI / 2
  12.     s, c = sincos_sub(Math::PI / 2 - x, n)
  13.     return [c, s]
  14.   when Math::PI / 2 .. Math::PI
  15.     s, c = sincos(Math::PI - x, n)
  16.     return [s, -c]
  17.   when Math::PI .. 2 * Math::PI
  18.     s, c = sincos(2 * Math::PI - x, n)
  19.     return [-s, c]
  20.   end
  21. end
  22.  
  23. def sincos_sub(x, n)
  24.   sign = 1; pow = 1.0; fact = 1; sin = 0.0; cos = 0.0
  25.   n.times do |i|
  26.     cos += sign * pow / fact
  27.     pow *= x
  28.     fact *= 2 * i + 1
  29.     sin += sign * pow / fact
  30.     pow *= x
  31.     fact *= 2 * i + 2
  32.     sign = -sign
  33.   end
  34.   [sin, cos]
  35. end
  36.  
  37. def main
  38.   puts '#deg: sin(err) cos(err)'
  39.   0.step(by: 5, to: 360) do |i|
  40.     x = i * Math::PI / 180.0
  41.     s, c = sincos(x, 1000)
  42.     next if s.nan? or c.nan?
  43.     ds = (s - Math.sin(x)).abs
  44.     dc = (c - Math.cos(x)).abs
  45.     puts "#{i}: #{s}(#{ds}) #{c}(#{dc})"
  46.   end
  47. end
  48.  
  49. main
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement