naquo

Ecuación Cuadrática - Ruby

Oct 25th, 2012
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.75 KB | None | 0 0
  1. module Cuadratica
  2.   require 'complex'
  3.   require 'mathn'
  4.   include Math
  5.   def a
  6.     h*b/(-2)
  7.   end
  8.   def b
  9.     -2*a*h
  10.   end
  11.   def c
  12.     a*h**2+k
  13.   end
  14.   def h
  15.     b/(-2*a)
  16.   end
  17.   def k
  18.     c-a*h**2
  19.   end
  20.   def f(x)
  21.     a*x**2+b*x+c
  22.   end
  23.   def inverse_f(y)
  24.     [sqrt((y-k)/a)+h, -sqrt((y-k)/a)+h]
  25.   end
  26.   def OriginOrdinate
  27.     f(0)
  28.   end
  29.   def Vertice
  30.     Point.new(h,k)
  31.   end
  32.   def Roots
  33.     inverse_f(0)
  34.   end
  35.   def to_s
  36.     "<a: #{a}, b: #{b}, c: #{c}, h: #{h}, k: #{k}>"
  37.   end
  38. end
  39.  
  40. class Point
  41.   attr_accessor :x, :y
  42.   def initialize(x, y)
  43.     @x = x
  44.     @y = y
  45.   end
  46.   def to_hash
  47.     {
  48.       :x => x,
  49.       :y => y
  50.     }
  51.   end
  52.   def to_a
  53.     [
  54.       [:x, x],
  55.       [:y, y]
  56.     ]
  57.   end
  58.   def to_s
  59.     "(%+.2f; %+.2f)" % [x, y]
  60.   end
  61. end
  62.  
  63. class Canonica
  64.   include Cuadratica
  65.   attr_accessor :a, :h, :k
  66.   def initialize(a, h, k)
  67.     @a = a
  68.     @h = h
  69.     @k = k
  70.   end
  71.   def to_explicita
  72.     Explicita.new(a, b, c)
  73.   end
  74.   def to_s
  75.     "%.1f(x%+.1f)^2%+.1f" % [a, -h, k]
  76.   end
  77. end
  78.  
  79. class Explicita
  80.   include Cuadratica
  81.   attr_accessor :a, :b, :c
  82.   def initialize(a, b, c)
  83.     @a = a
  84.     @b = b
  85.     @c = c
  86.   end
  87.   def to_canonica
  88.     Canonica.new(a, h, k)
  89.   end
  90.   def to_s
  91.     "%.1fx^2%+.1fx%+.1f" % [a, b, c]
  92.   end
  93.   def f(x)
  94.     a*(x-h)**2+k
  95.   end
  96. end
  97.  
  98. class EcuacionCuadratica
  99.   include Cuadratica
  100.   def initialize(hashes={})
  101.     hashes.each {|n,v| incognita(n) {v}}
  102.   end
  103.   def incognita(name, &block)
  104.     if(self.method(name) rescue false)
  105.       self.class.send(:define_method, name, &block)
  106.     else
  107.       raise "Incognita \"#{name}\" inexistente"
  108.     end
  109.   end
  110.   def to_canonica
  111.     Canonica.new(a, h, k)
  112.   end
  113.   def to_explicita
  114.     Explicita.new(a, b, c)
  115.   end
  116. end
Advertisement
Add Comment
Please, Sign In to add comment