How to solve linear equations with Ruby

Today I will show you how you can solve easy (currently only +/-) linear equations with Ruby. Imagine that you are a pupil in the elementary school and you solved a linear equation but you don’t know if your result is correct. This litte Ruby script could show you the correct result. I think, this is pretty cool!

The problem:

Solve this linear equation: -3.3x+89+78x=95.3+76.5x

Your solution:

Use Ruby. (:

To solve an equation with Ruby you have to know how you would solve the equation on a piece of paper. I would solve the equation as I learned it in school:

-3.3x+89+78x = 95.3+76.5x | Sum all x.

89+74.7x = 95.3+76.5x | Bring all x on one side -74.7x

89 = 95.3 + 1.8x | - 95.3

-6.3 = 1.8x | /1.8

-3.5 = x

Now we have to “convert” this calculating method, into an (easy to understand) algorithm.

Steps:

First step: Ask the user for an equation. Split the equation string into “numbers” and into two parts, one part before “=” and one after.

first_code_piece

Second step: Get all x onto one side, get all numbers to other side. Divide the number of x’s by the number of numbers and print the result. Expressed in Ruby this will look like:

second_piece_of_code

I think the two code pieces are self explaining, I will not take you through every line. (;. You can download the whole code from here. But remember this algorithm can currently only solve +/- linear equations!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *