Last active
August 29, 2015 14:17
-
-
Save wsams/ba9c04e50acd1dd303a4 to your computer and use it in GitHub Desktop.
Create an (X, Y) plane suitable for graphing equations in Ruby.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "rubygems" | |
require 'png' | |
class RubyGraph | |
attr_accessor :x_precision | |
attr_accessor :y_precision | |
attr_accessor :x_pos_units | |
attr_accessor :y_pos_units | |
attr_accessor :x_neg_units | |
attr_accessor :y_neg_units | |
def initialize | |
@x_precision = 1 | |
@y_precision = 1 | |
@x_pos_units = 200 | |
@y_pos_units = 200 | |
@x_neg_units = 200 | |
@y_neg_units = 200 | |
end | |
def fn x | |
x | |
end | |
def graph | |
x_start = -1 * @x_neg_units; | |
x_end = @x_pos_units; | |
y_start = -1 * @y_neg_units; | |
y_end = @y_pos_units; | |
canvas = PNG::Canvas.new(@x_pos_units + @x_neg_units + 1, @y_pos_units + @y_neg_units + 1); | |
x_start.upto(x_end) do |x| | |
y_start.upto(y_end) do |y| | |
# 255:white 0:black | |
r = g = b = x == 0 || y == 0 ? 0 : 255 | |
if y == fn(x) | |
r = 255 | |
g = 0 | |
b = 0 | |
end | |
canvas[x + @x_neg_units, y + @y_neg_units] = PNG::Color.new(r, g, b) | |
end | |
end | |
png = PNG.new(canvas) | |
png.save("graph.png") | |
end | |
end | |
rg = RubyGraph.new | |
rg.graph |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment