symbolic icon indicating copy to clipboard operation
symbolic copied to clipboard

Symbolic math for ruby

Symbolic math for ruby.

== Installation

Symbolic needs Ruby 1.9.

gem install symbolic

== Introduction

This gem can help you

  • if you want to get a simplified form of a big equation
  • if you want to speed up similar calculations
  • if you need an abstraction layer for math

Symbolic doesn't have any external dependencies.

== Tutorial

First, you need to create a symbolic variable.

x = var

you can set a name of variable (useful if you print equations)

angle = var :name => 'θ'

or starting value

pi = var :value => 3.14

or bind its value to a proc

y = var { x ** 2 }

you can set a value for already created variable

x.value = 3

Now, you can do any math operations with it.

f = 2x + 1 puts f # => 2x+1

To get value of symbolic expression you just call value:

f.value # => 7

You can accomplish the same thing with subs:

f.subs(x,3) # => 7

Or make a more complicated substitution:

f.subs(x,x2) # => 2*x2+1

If symbolic expression contains variables without value then it returns nil.

z = var (z+1).value # => nil

All symbolic expression are automatically simplified when created:

0 * x # => 0 2 + x + 1 # => x + 3 -(x-y) + 2*x # => x + y (x**2)3 / x # => x5

etc. (more examples can be found in symbolic_spec.rb)

If you need to use a function from Math module with symbolic variable, use Symbolic::Math module.

cos = Symbolic::Math.cos(x) x.value = 0 cos.value # => 1.0

You can get a list of variables from symbolic expression:

(x+y+1).variables # => [x, y]

So you can get a list of variables without value:

(x+y+1).variables.select {|var| var.value.nil? }

You can get information about the number of different operations used in a symbolic expression:

f = (2x-y+2)x-2*(xy) f.operations # => {"+"=>1, "-"=>2, "*"=>3, "/"=>0, "**"=>1, "-@"=>0}

You can also take derivitives and do taylor expansions:

Symbolic::Math.cos(x**2).diff(x)

=> -2*(sin(x**2))*x

Symbolic::Math.cos(x).taylor(x,0,3)

=> -0.5*x**2+1.0

== TODO

  • a lot of refactoring (code is pretty messy at this stage)
  • plotting capabilities
  • integrals
  • thorough documentation

== Author

brainopia (ravwar at gmail.com).

I am ready to help with any questions related to Symbolic. I welcome any contribution.