-2

Here is the code for my quadratic calculator:

puts "A?"
a = gets.to_f
puts "B?"
b = gets.to_f
puts "C?"
c = gets.to_f

d = (-b + (((b**2) - (4*a*c))**(1/2)))/(2*a)
puts d

f = (-b - (((b**2) - (4*a*c))**(1/2)))/(2*a)
puts f

However, the answers are not always correct.

For example, I do not get imaginary numbers.

What am I doing wrong?

Sebastián Palma
  • 32,692
  • 6
  • 40
  • 59
  • 1
    hi and welcome to stackoverflow! could you specify what language this is this (with a tag)? and please format the code appropriately! thanks – codeling Sep 11 '12 at 12:45
  • that is how i formatted it, i'm not sure how i would do it otherwise! I'm new to this and running it through ruby (terminal on my mac) – user1650578 Sep 11 '12 at 17:28

1 Answers1

1

You were doing all of your calculations with real numbers. You need to require 'complex' to get complex numbers. I kept your program structure and added complex numbers to it.

One other thing, in your program you had 1/2 but since these are integers, this division results in 0 since integer division throws away the fractional result (eg. 7/2 is 3).

#!/usr/bin/ruby

require 'complex'

# very small real number, consider anything smaller than this to
# be zero
EPSILON = 1e-12

def print_complex(n)
    # break n into real and imaginary parts
    real = n.real
    imag = n.imag

    # convert really small numbers to zero
    real = 0.0 if real.abs < EPSILON
    imag = 0.0 if imag.abs < EPSILON

    # if the imaginary part is zero, print as a real
    if n.imag == 0.0
       puts real
    else
       puts Complex(real, imag)
    end
end

puts "A?"
a = gets.to_f

puts "B?"
b = gets.to_f

puts "C?"
c = gets.to_f

# Turn the real numbers into complex numbers
ac = Complex(a, 0)
bc = Complex(b, 0)
cc = Complex(c, 0)

dc = (-bc + (((bc**2) - (4*ac*cc))**(1.0/2)))/(2*ac)
print_complex(dc)

fc = (-bc - (((bc**2) - (4*ac*cc))**(1.0/2)))/(2*ac)
print_complex(fc)
vacawama
  • 150,663
  • 30
  • 266
  • 294
  • Welcome to StackOverflow. If you find this answer correct, please select the "check mark" below the number on the left, and increment the count by selecting the up arrow above the number. Thanks. – vacawama Sep 13 '12 at 01:02