Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

perl program

Status
Not open for further replies.

9875

Programmer
Jan 27, 2005
1
CA
I need a solution for 2 equations with 2 unknowns
It can be done mathematically but putting it into the code is tough. ANy help is appreciated.
here is some test data

2x -3y = -8
x + y =6
(2,4)

4x - 2y = -28
-0.5x + y = 5
(-6,2)
 
you want to make a program that can solve whatever
'2 equations with 2 unknows' problem?

and if yes

you know that even with 2 unknowns, someone can make a realy difficult problem to solve, and realy complex.

or you just want to print the resolts from those two you just wrote?

the program you want to make will take any input from the command line and if yes what?

we have to know what exactly you want to make

 
This is not that difficult.
my ($x1, $y1, $c1);
my ($x2, $y2, $c2);

$y = (($c2*$x1) - ($c1*$x3)) / (($y2*$x1) - ($y1*$x3));
Then calculate $x similarly.
 
Sorry, $x3 should be $x2.

my ($x1, $y1, $c1);
my ($x2, $y2, $c2);

$y = (($c2*$x1) - ($c1*$x2)) / (($y2*$x1) - ($y1*$x2));
Then calculate $x similarly.
 
Ruby:
Code:
def solve( *eqs )
  ary = []
  eqs.each { |x|
    # Remove spaces.
    x.gsub!( /\s+/, "")
    # If variable lacks coefficient, use 1.
    x.gsub!( /(\d*\.?\d*)[xy]/ ) {|m| m="1"+m if ""==$1; m}
    ary << x.split( /[xy=]+/ )
  }
  # Remove +'s and convert strings to floats.
  ary.map!{|row| row.map!{|s| s.sub(/\+/,"")
    s.to_f  }}
  p ary
  mul = ary[0][1] / ary[1][1] * -1
  ary[1].map!{ |f| f*mul }
  x = (ary[0][2]+ary[1][2])/(ary[0][0]+ary[1][0])
  y = (ary[0][2]-ary[0][0]*x)/ary[0][1]
  [x, y]
end

x,y = solve( "2x -3y = -8", "x + y =6" )
printf "%g,%g\n", x, y

x,y = solve( "4x - 2y = -28", "-0.5x + y = 5" )
printf "%g,%g\n", x, y
The output is
[tt]
[[2.0, -3.0, -8.0], [1.0, 1.0, 6.0]]
2,4
[[4.0, -2.0, -28.0], [-0.5, 1.0, 5.0]]
-6,2
[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top