Polynomials

Example App

Checkout my Example App to see the gem in action!

Usage

require 'polynomials'
require 'gnuplot'
include Polynomials


polynomial = Polynomial.parse(ARGV[0])

points =  polynomial.roots | polynomial.local_extrema | polynomial.inflection_points

max_x =  points.max_by(&:x)
min_x =  points.min_by(&:x)
max_x = max_x == 0 ? max_x.x : 1
min_x = min_x == 0 ? min_x.x : -1

difference = (max_x-min_x).abs

start = min_x - difference/4.0
stop = max_x + difference/4.0
step = (start-stop).abs/1000.0

pointset = polynomial.pointset(start,stop,step)
data_x=  pointset.map(&:first)
data_y = pointset.map(&:last)

Gnuplot.open do |gp|
  Gnuplot::Plot.new(gp) do |plot|
    plot.xrange "[#{start}:#{stop}]"
    plot.title  "Polynomial"
    plot.ylabel "f(x)"
    plot.xlabel "x"
    plot.grid
    plot.data << Gnuplot::DataSet.new( [data_x,data_y] ) do |ds|
      ds.with = "lines"
      ds.linewidth = 0.2
      ds.title =  "f(x) = #{polynomial}"
      ds.smooth
    end

    [:inflection_point,:root, :maximum, :minimum].each do |kind_of_point|
      selected_points = points.select(&:"#{kind_of_point}?")
      plot.data << Gnuplot::DataSet.new([selected_points.map(&:x), selected_points.map(&:y)]) do |ds|
        ds.with = "points"
        ds.linewidth = 2
        ds.title = kind_of_point.to_s.pluralize.titleize
      end
    end
  end
end

Bash Command

 % ruby examples/plot_only_mutual_data.rb '20.432 x^4 - 17.75 x^3 - 20x^2 + 5 x -50'

Output:

<img src=“”>

Contributing to polynomials

Copyright © 2011 Manuel Korfmann. See LICENSE.txt for further details.