roots_of_a_quadratic_function.sf 568 B

12345678910111213141516171819202122232425262728293031
  1. #!/usr/bin/ruby
  2. #
  3. ## https://rosettacode.org/wiki/Roots_of_a_quadratic_function
  4. #
  5. var sets = [
  6. [1, 2, 1],
  7. [1, 2, 3],
  8. [1, -2, 1],
  9. [1, 0, -4],
  10. [1, -1e6, 1],
  11. ];
  12.  
  13. func quadroots(a, b, c) {
  14. var root = (
  15. (b**2 - 4*a*c) -> complex.sqrt
  16. );
  17.  
  18. a.complex!;
  19. b.complex!;
  20.  
  21. [(-b + root) / (2 * a),
  22. (-b - root) / (2 * a)];
  23. }
  24.  
  25. sets.each { |coefficients|
  26. say ("Roots for #{coefficients.dump}",
  27. "=> (#{quadroots(coefficients...).join(', ')})");
  28. }