Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re: How would you solve a user-inputted simple one-variable Linear Equation

by bitingduck (Chaplain)
on Apr 25, 2015 at 17:21 UTC ( [id://1124689]=note: print w/replies, xml ) Need Help??


in reply to How would you solve a user-inputted simple one-variable Linear Equation

For a simple linear equation with an arbitrarily complex input stream, e.g. 2+3x+7(x+27)-6 you can probably do it with a minimum of conditionals. The hard part is writing a parser, but it's also entertaining. How I might do it, based on not spending much time on it and not having done one in a while is:

a) Write a parser that splits on the equal sign and multiplies everything out to eliminate parentheses, so my expression above would be 2+3x+7x+189-6.

b) do a second pass where you look at each term and add it into a pair of accumulators, one for the constants and one for the slopes. When you process the righthand side, multiply everything by -1 before you add it.

Now you have something like 3235643596 in the slope accumulator (corresponding to the "x" terms) and 998396 in the constant accumulator. Do a simple division of one by the other and you're done.

Writing the parser is the hard part, and it shouldn't be that hard for your case (you should be able to do it with a little recursive chunk of code)

  • Comment on Re: How would you solve a user-inputted simple one-variable Linear Equation

Replies are listed 'Best First'.
Re^2: How would you solve a user-inputted simple one-variable Linear Equation
by nat47 (Sexton) on Apr 25, 2015 at 17:30 UTC
    Okay, this makes a decent amount of sense to me, thanks. Where is the = sign in your equation?

      I was lazy and left off the righthand side... if you have something like 2+3x+7(x+27)-6= 23x-45-(145+62-5)x then you would just start with a split on the = sign and parse the two halves separately.

        Thanks, I appreciate it! Figuring out how to distribute with () and x's is turning out to be more challenging than I thought without using modules like Math::Symbolic

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1124689]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (4)
As of 2024-04-19 04:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found