PDA

View Full Version : Numerical Quadratic Equation Solver

JayT
09-17-2007, 10:57 PM
Here is a function I threatened to post earlier.
It works in PHP 4 and 5.

It simply computes the numerical solutions,
real and imaginary, for a standard quadratic
equation of the general form

Ax² + Bx + C = 0

USAGE EXAMPLES

To find the real roots of the quadratic equation:

2x² + 14x - 156 = 0

/*

Returned result

x1 = -13
x2 = 6

*/

To find the complex (imaginary) roots of the quadratic equation:

16x² - 10x + 4 = 0

/*

Returned result

x = 0.3125 ± 0.39031237489989988786 i

The (i) at the end indicates a complex (imaginary) root.

*/

Here is the PHP code for the function:

/*

equation of the general form

Ax² + Bx + C = 0

for numerical roots x1 and x2

The solutions may be real or complex (imaginary).

The computations are performed in arbitrary precision
with output precision truncated to 16 decimals.

*/

{

// ---------------------

\$A = trim(\$Aarg);
\$B = trim(\$Barg);
\$C = trim(\$Carg);

// --------------------------------
// Set internal decimals precision.

\$DP = 20;

// ------------------------------------------
// Compute discriminant D. If negative, then
// the solutions are complex (imaginary).

\$w1 = bcMul(\$B, \$B, \$DP); // B²

\$w2 = bcMul("4", bcMul(\$A, \$C, \$DP), \$DP); // 4AC

\$D = bcSub(\$w1, \$w2, \$DP);

// -----------------------------------------------
// Determine if quadratic root is real or complex.

\$i = "";

if (bcComp(\$D, "0", \$DP) < 0)

{
\$i = "<B> i</B>"; \$D = bcSub("0", \$D, \$DP);
}

// --------------------------
// Compute values of u and v.

\$u = bcDiv(bcSub("0", \$B, \$DP), bcMul("2", \$A, \$DP), \$DP); // -B/2A

\$w3 = bcSqRt(\$D, \$DP); // SqRt(B² - 4AC) = SqRt(D)

\$v = bcDiv(\$w3, bcMul("2", \$A, \$DP), \$DP); // SqRt(B² - 4AC) / 2A

// -----------------------------
// Do this if roots are complex.

if (\$i != "")
{
\$u = RTrim(RTrim(\$u, "0"), ".");
\$v = RTrim(RTrim(\$v, "0"), ".");
return "<PRE>x = \$u &plusmn; \$v\$i</PRE>";
}

// --------------------------
// Do this if roots are real.

\$x1 = RTrim(RTrim(bcSub(\$u, \$v, 16), "0"), ".");
\$x2 = RTrim(RTrim(bcAdd(\$u, \$v, 16), "0"), ".");
return "<PRE>x1 = \$x1\nx2 = \$x2</PRE>";

Hope someone finds this useful.

Cheers!

:)

Moonbat
09-18-2007, 05:48 AM
A few years ago, this would've helped me pwn my homework, but this still is useful (but not nearly as useful as it would've been had I met you before this time). Thanks a load for this :D

P.S. - Can you make a program that can factor polynomials (anywhere from binomials to hexanomials) please?

JayT
09-23-2007, 07:45 PM
A few years ago, this would've helped me pwn my homework, but this still is useful (but not nearly as useful as it would've been had I met you before this time). Thanks a load for this :D

P.S. - Can you make a program that can factor polynomials (anywhere from binomials to hexanomials) please?

Factoring is a complicated process.
The three main reasons are because trial an error is involved in some cases, in some other cases factoring is impossible and in other cases, some factors can be mixed (real and complex).

I'll have to study that problem more, but it's a good idea.

I crossed swords with that problem quite a few times. It left some scars.

:)

Ezekiel
09-24-2007, 02:54 AM
I'm wondering, do you have anything on your site (or code snippets) relating to surds?

I'm too lazy to do another one of these:

http://www.divshare.com/image/2087271-eab

Edit: I got five tails on my first try of your random coin flipper! What are the chances of that? I guess I've won the internet now.

JayT
09-24-2007, 01:39 PM
I'm wondering, do you have anything on your site (or code snippets) relating to surds?

I'm too lazy to do another one of these:

http://www.divshare.com/image/2087271-eab

Edit: I got five tails on my first try of your random coin flipper! What are the chances of that? I guess I've won the internet now.

Yes! You've won the Internet! Take it home with you!
LOL

The chances of 5 tails in a row is identical to the chances of 5 heads in a row.

Actually 1/32

1 : (Possible outcomes per trial) ^ Trials = 1:(2 ^ 5) = 1:32

Odds of tossing n heads (or tails) in a row = 1:(2 ^ n)

Odds of getting 10 true/false questions 100&#37; wrong/correct by random guessing alone:

1:(2 ^ 10) = 1:1024

etc.

The things on that site are basically my PHP learning experiments.

**************

If you mean the essential rules of working with surds, I don't have too much at this time. Still updating some things in the background.

That math sheet image brings back some memories.
LOL

I do have lots of math notes that I'm slowly converting into PHP web pages, like I did with the quadratic function. Some are on the subject of surds, but not yet made into web pages.

One reason it takes me so long is because I'm fanatically fussy about quality. I test a page to death to make sure it works correctly.

I didn't exactly expect many would be too interested, so I wasn't in a rush. Math usually scares people.

:)

Math is much easier to learn when there is a real-world physical problem to which to apply it and see what the numbers are for and where they come from and how they relate to the problem.

That's my focus - practical math. They spend too much time on theory before the student has had a chance to relate it to reality. Much harder to learn it that way. Schools are in such a mad rush these days.

When is the last time you encountered a problem in the real world (other than a school exam) that you would tackle by using a quadratic equation? Would you recognise such a problem if it was in front of you? Schools seem to miss this point.

At the moment, one of my web hosts is slowing me down. I was supposed to be moved to a different server back on the 21st so both of my sites would be using PHP5, but it hasn't happened yet, so I can't get much done until they do it.

Time to send them an email and inquire about the problem.

Ezekiel
09-25-2007, 03:22 AM
Yes! You've won the Internet! Take it home with you!
LOL

The chances of 5 tails in a row is identical to the chances of 5 heads in a row.

Actually 1/32

1 : (Possible outcomes per trial) ^ Trials = 1:(2 ^ 5) = 1:32

Odds of tossing n heads (or tails) in a row = 1:(2 ^ n)

Odds of getting 10 true/false questions 100&#37; wrong/correct by random guessing alone:

1:(2 ^ 10) = 1:1024

Yeah I'm pretty good with probability, but it's nice to have someone do the work for you ;).

So they're all exponents of two. Makes sense.

I still think 1/32 is an impressive gamble to win at. Yesterday must have been my lucky day.

Aw crap, what does that mean for today then?

If you mean the essential rules of working with surds, I don't have too much at this time. Still updating some things in the background.

Oh god, this means I'll have to do homework. You can not underestimate the seriousness of this situation.

That math sheet image brings back some memories.

Math is much easier to learn when there is a real-world physical problem to which to apply it and see what the numbers are for and where they come from and how they relate to the problem.

That's my focus - practical math. They spend too much time on theory before the student has had a chance to relate it to reality. Much harder to learn it that way. Schools are in such a mad rush these days.

When is the last time you encountered a problem in the real world (other than a school exam) that you would tackle by using a quadratic equation? Would you recognise such a problem if it was in front of you? Schools seem to miss this point.

No, I certainly can not think of any real-life application of these things; especially surds.

That is of course unless I plan to live a highly-scientific life and become a world-renowned rocket-scientist, but that's not really how I roll [read: too lazy].

At the moment, one of my web hosts is slowing me down. I was supposed to be moved to a different server back on the 21st so both of my sites would be using PHP5, but it hasn't happened yet, so I can't get much done until they do it.

www.nearlyfreespeech.net

Pay for what you use. I have so far paid about \$10 to keep my site running for many months. That's with MySQL, mail-forwarding -- the whole deal.

Give them a try.

JayT
09-25-2007, 03:49 PM
Yeah I'm pretty good with probability, but it's nice to have someone do the work for you ;).

So they're all exponents of two. Makes sense.

I still think 1/32 is an impressive gamble to win at. Yesterday must have been my lucky day.

Aw crap, what does that mean for today then?

Hint: You have used up your luck quota for the week! You should hide under the bed and pray until the sun sets on Friday.

You find surds in probability too.
There's no escaping them!
Give up - surrender to them while there's still hope!
LOL

Oh god, this means I'll have to do homework. You can not underestimate the seriousness of this situation.

Been there, done that. I have a million nieces and nephews wanting me to do their homework. Then I'd have no time for my homework!
LOL
I can sometimes help with homework, but doing it for them is a no-no.

To horrible to contemplate.
LOL

In school, I was bad at math at the time - and everything else too. I have a serious hearing problem so I was labelled 'slow'. Most of what I learned, I learned after school, not during.

Where having to hear is important, is where I have the greatest problem. Math doesn't require hearing to learn it, so I learned it more on my own, since I couldn't get confused to death by what the teacher said.

No, I certainly can not think of any real-life application of these things; especially surds.

That is of course unless I plan to live a highly-scientific life and become a world-renowned rocket-scientist, but that's not really how I roll [read: too lazy].

Lots of rather ordinary problems apply surds (AKA roots).

A square root is a surd. If you have a square with surface area X, the length of one edge is the square root of the number X.

A cube root is a surd. If you have a cube with cubic volume X, the length of one edge is the cube root of the number X.

Surds were originally part of ancient trigonometry, the study of triangles and the laws pertaining to them, and typically used to find distances between points. They were (and still are) used by land surveyors and navigators and teachers who like to frighten children with them.

Here's a simple example of a surd in action. If you walked 30 yards to the north and 40 yards to the west, how far away would you then be from your original starting point measured along a straight line connecting the two endpoints?

Distance = SqRt(30&#178; + 40&#178;) = SqRt(900+1600) = SqRt(2500) = 50 yards

So, you would end up 50 yards from where you started.

The distances above represent the differences in the coordinates of the endpoints, with respect to where you started, (X=30 and Y=40, or vice versa), and 50 yards is the shortest straight-line distance between the starting and ending points.

This means that if you walked 30 yards north and then 40 yards west, you would have walked 30+40 = 70 yards. If you had walked in a straight line directly to the destination point, you would have only had to walk 50 yards instead.

You simply sum the squares of the differences between the beginning and endpoint coordinates and the square root of the combined squared sums is the straight line distance between those points.

Distance = SqRt(X&#178; + Y&#178;)

Surdus = Latin for deaf, mute or dull.

When translating Greek mathematics into Latin, scholars translated the Greek word (alogos = without reason, irrational) into 'surdus'. That should tell you something!
LOL

Most teachers are surds!

Do you know how to directly calculate a square root from scratch? I mean by direct calculation, not by trial and error or using anything but the basic four arithmetic operations.

It's not difficult, but I doubt they teach this long lost art anymore in school.

If society had to start over, most of the school-trained "educated" of today would have no advantage to help rebuild it because they never really learned the basics of how to make the bricks in the foundations upon which it was built.

They can only use the existing bricks, but they seem to have forgotten how to make new ones when the supply runs out.

Never get trapped on a deserted island with a teacher in charge.

LOL

www.nearlyfreespeech.net

My PHP5 problem was fixed.
Now both sites run PHP 5.

:)

JayT
09-25-2007, 04:12 PM
Yeah I'm pretty good with probability, but it's nice to have someone do the work for you ;).

That is of course unless I plan to live a highly-scientific life and become a world-renowned rocket-scientist, but that's not really how I roll [read: too lazy].

That's the one thing everyone has to do for himself.

Unfortinately, the way the educational system works, they make hard work out of things that are far more simple than they would have you believe.

You seem pretty bright - develop it in spite of the system!

Do you feel like a zombie in the morning?
Maybe you aren't getting enough brains in your diet.

http://www.brains4zombies.com

:)

You like probability?

Here's a probability problem for you.

If I were to flip a fair coin 10 times, what is the probability that the final result will be either heads or tails?

A: 25&#37;
B: 50%
C: 75%
D: 100%
E: None of the above answers

.

Ezekiel
09-26-2007, 03:13 AM
You like probability?

Here's a probability problem for you.

If I were to flip a fair coin 10 times, what is the probability that the final result will be either heads or tails?

A: 25%
B: 50%
C: 75%
D: 100%
E: None of the above answers

.

50%, AKA half, AKA 1/2, AKA 0.5. Each result is independent of the others unless the question specifically mentions a required sequence of events.

If you said "what is the probability that all of them would be heads?", it would be (1/2) ^ 10.

JayT
09-26-2007, 09:13 AM
50&#37;, AKA half, AKA 1/2, AKA 0.5. Each result is independent of the others unless the question specifically mentions a required sequence of events.

If you said "what is the probability that all of them would be heads?", it would be (1/2) ^ 10.

Sneaky me. I'm so evil, the Devil offered me a job!

Actually, it's a trick question.

In probability theory, the wording of the probability question you wish to resolve is critical, especially if it involves the words AND|OR|NOT.

The probability is 100% that the result will be either heads or tails.

Here's why:

If you asked me to predict the result of any coin flip and I said "It will be Heads", then there is a 50% probability I would be correct.

If you asked me to predict the result of any coin flip and I said "It will be Tails", then there is a 50% probability I would be correct.

If you asked me to predict the result of any coin flip and I said "It will be either heads or tails", then I am 100% correct because it will indeed be either one or the other. I can't be wrong. So the probability is 100% in this case.

ONE possibility is covered. ONE way to lose.

Probability of Tails = 50%
ONE possibility is covered. ONE way to lose.

Probability of either Heads or Tails = 50% + 50% = 100%
BOTH possibilities are covered. NO way to lose.

The 10 was thrown in as a distraction and is entirely irrelevant to the problem and can be ignored, as you obviously noticed.

The same logic applies to a rolled die.

If I predicted that the result of any roll would be either 1 or 2 or 3 or 4 or 5 or 6, then I'm 100% correct for exactly the same reason. There is a 100% probability that the result will be one or another of those outcomes.

Bet your best friend 10 million of your favourite monetary units that you can correctly predict which horse will win a certain race. Then place a bet on every horse. When the race is over. You will be rich, because there is a 100% probability that one of the horses you bet on will be the winner. The money you lost on the other losing horses will be more than made up for when your former friend pays off your bet.

LOL

:)

Ezekiel
09-26-2007, 03:28 PM
Hint: You have used up your luck quota for the week! You should hide under the bed and pray until the sun sets on Friday.

Ah, but I define the end of the week as Sunday. This makes my situation somewhat worse.

You find surds in probability too.
There's no escaping them!
Give up - surrender to them while there's still hope!
LOL

I understand them when make the effort to, but it's the effort I'm lacking. I'll post here when I get the results from the homework I showed you ;).

In school, I was bad at math at the time - and everything else too. I have a serious hearing problem so I was labelled 'slow'. Most of what I learned, I learned after school, not during.

Where having to hear is important, is where I have the greatest problem. Math doesn't require hearing to learn it, so I learned it more on my own, since I couldn't get confused to death by what the teacher said.

Now you're laughing at the teachers who called you 'slow'; probably now being at the level of a rocket-scientist.

I also do most of my learning after school, but for different reasons.

Lots of rather ordinary problems apply surds (AKA roots).

I thought surds were only defined as the nth root of an number when irrational?

I was under the impression that sqroot(25) isn't a surd, but sqroot(3) is, since the square root of three is an irrational number, but the square root of 25 can be resolved to 5, thus is rational.

Incidentally, why isn't there a damn root character on my keyboard? The people who designed ASCII (or whatever character set I'm using now) really failed there.

If you have a square with surface area X, the length of one edge is the square root of the number X.

Yup, because the area of a square is both sides multiplied together, and both are equal if it's a square, so you're multiplying same number by itself, thus squaring it.

If you have a cube with cubic volume X, the length of one edge is the cube root of the number X.

With the same reasoning as above, except this time in three dimensions.

Surds were originally part of ancient trigonometry, the study of triangles and the laws pertaining to them, and typically used to find distances between points.

I remember my teacher saying something about them relating to trigonometry, I think. Pythagoras' stuff involves square roots.

They were (and still are) used by land surveyors and navigators and teachers who like to frighten children with them.

More predominantly with the latter.

Here's a simple example of a surd in action. If you walked 30 yards to the north and 40 yards to the west, how far away would you then be from your original starting point measured along a straight line connecting the two endpoints?

I only work with the metric system, but my answer is below.

We are looking to find the length of the hypotenuse side -- since it's a right-angled triangle, Pythagoras can help us with a really simple solution.

So,

length of hypotenuse squared = 30 squared + 40 squared.

Then square root the result, and you have the distance from the origin.

Surdus = Latin for deaf, mute or dull.

When translating Greek mathematics into Latin, scholars translated the Greek word (alogos = without reason, irrational) into 'surdus'. That should tell you something!
LOL

Most teachers are surds!

My maths teachers are actually quite cool and seem to know what they're doing; I haven't got much to complain about. At the moment, my 'pure math' teacher tries to make as many Star Wars references as possible in each 1-hour class.

It takes some imagination to weave "the dark side", "Darth Vader" and so on into mathematical explanations.

In case anyone was wondering, we call it 'maths' here in the UK. After all, it's not just one mathematic.

Do you know how to directly calculate a square root from scratch? I mean by direct calculation, not by trial and error or using anything but the basic four arithmetic operations.

It's not difficult, but I doubt they teach this long lost art anymore in school.

Sounds like my brain would explode if you posted an explanation here.

If society had to start over, most of the school-trained "educated" of today would have no advantage to help rebuild it because they never really learned the basics of how to make the bricks in the foundations upon which it was built.

They can only use the existing bricks, but they seem to have forgotten how to make new ones when the supply runs out.

Never get trapped on a deserted island with a teacher in charge.

It's like computers; both hardware and software. People are gradually learning how to be users rather than low-level programmers/electronics gurus.

Sneaky me. I'm so evil, the Devil offered me a job!

Actually, it's a trick question.

Ah, you bastard! I thought the question was asking me what it would be for each one (heads or tails) individually.

Very good. I fell right into your trap. I bet you logged on today, took a sip of coffee and thought "got him".

Bet your best friend 10 million of your favourite monetary units that you can correctly predict which horse will win a certain race. Then place a bet on every horse. When the race is over. You will be rich, because there is a 100&#37; probability that one of the horses you bet on will be the winner. The money you lost on the other losing horses will be more than made up for when your former friend pays off your bet.

Sounds like a plan to win at life.

JayT
09-27-2007, 02:37 PM
Ah, but I define the end of the week as Sunday. This makes my situation somewhat worse.

You could always change your religion to one that uses a different calendar and considers maths a sin.
LOL

In some religions a year is considerably less than 365 days.

Now you're laughing at the teachers who called you 'slow'; probably now being at the level of a rocket-scientist.

I'm not actually laughing at the teachers, but I am a bit disgusted with them when I look back in hindsight. Many of the things they wanted me to learn were actually quite simple, but the methods they used for instruction made even simple concepts seem like mind-numbing drudgery. They focused more on rote memory rather than true, in-depth comprehension of the subject. As long as we could remember it long enough to pass next week's exam, that was considered good enough.

Worst of all was lack of physical examples to show how it all related to the real world and what kind of problems we would later encounter in life to which we could apply that education.

I'm no rocket scientist. Just a little above average at best. And only at scientific things. Outside my interests, I'm a dunce.
LOL

I also do most of my learning after school, but for different reasons.

No teachers around to confuse you.

I thought surds were only defined as the nth root of an number when irrational?

I was under the impression that sqroot(25) isn't a surd, but sqroot(3) is, since the square root of three is an irrational number, but the square root of 25 can be resolved to 5, thus is rational.

That's correct. But, since a root symbol is sometimes erroneously called a surd symbol, rather than the more correct radical symbol (I've witnessed teachers do this more than once), people often forget that it is only a true surd if its numerical value is irrational. The distinction has blurred over the years and some teachers make this mistake too of calling ALL square or cube roots surds, which is not true in those cases where the root value is an integer or a terminal fraction.

Incidentally, why isn't there a damn root character on my keyboard? The people who designed ASCII (or whatever character set I'm using now) really failed there.

If the web browser can handle it, and you want to display a radical symbol in a web page, the code for it is:

HTML entity code 8730

or

Try this in PHP

TEST
√2

Do you see the square root of 2 below the word TEST in your browser ?

Interesting historical note:

I only work with the metric system, but my answer is below.

Actually, the formula is dimensionless. If you preferred to imagine that yards were metres instead, the numerical value would still be the same, only it would mean metres instead of yards.

I'm comfortable with metrics, since practically every scientific computation I do applies the SI system.

We are looking to find the length of the hypotenuse side -- since it's a right-angled triangle, Pythagoras can help us with a really simple solution.

So,

length of hypotenuse squared = 30 squared + 40 squared.

Then square root the result, and you have the distance from the origin.

Exactly.

It also works in 3, 4, 5, ... dimensions the same way.

My maths teachers are actually quite cool and seem to know what they're doing; I haven't got much to complain about. At the moment, my 'pure math' teacher tries to make as many Star Wars references as possible in each 1-hour class.

It takes some imagination to weave "the dark side", "Darth Vader" and so on into mathematical explanations.

In case anyone was wondering, we call it 'maths' here in the UK. After all, it's not just one mathematic.

I've noted they use 'maths'. Wasn't exactly sure why. But then I don't pick fights with millions of irrational people who drive on the wrong side of the road.
LOL

Sounds like my brain would explode if you posted an explanation here.

I said it was a simple procedure.
Since the process was discovered hundreds of years ago, long before calculators, it can't be too complicated for modern man to rediscover it!
LOL

Imagine you have a table of square roots carried out to only 3 decimal places.
You also have an old calculator that only has the four basic arithmetic operations.

But, horror or horrors - I need the square root of 5 to at least 6 decimals, but the table only goes to 3 decimals and the old calculator has no square root function.

My table says the square root of 5 is 2.236, so how do I determine a better approximation to more than 3 decimals ?

The simple formula in PHP is:

// \$x = Number whose square root we need
// \$a = First approximation to the square root of \$x
// \$b = A better approximation to the square root of \$x

\$b = (\$x/\$a + \$a) / 2;

If you take the resulting \$b and then substitute it for \$a and repeat the process, each new value of \$b will be a better and closer approximation to the square root. This process converges rapidly.

As a loop iteration process, the output from the previous cycle is the new input to the next cycle. Each cycle producing a better value than the previous until you quickly grind out the square root value to the limits of precision of the calculator or computer program.

For the square root of 5 example above:

\$x = 5;
\$a = 2.236;

\$b = (\$x/\$a + \$a) / 2; // = 2.2360679785331

print "\$b<BR>";

print sqrt(5) . "<BR>"; // Actual PHP value = 2.2360679774998

// Difference
print bcSub(\$b, sqrt(5), 13);

Starting with 2.236 as the 1st approximation gives
\$b = 2.2360679785331

The difference between the correct value and \$b is

\$b - SqRt(5) = 0.00000000103330

So we went from 3 decimals of precision to 8 decimals of precision in one cycle!

If we repeated the process, substituting \$b for \$a in the formula and computing a new \$b value we get

\$x = 5;
\$a = 2.2360679785331;

\$b = (\$x/\$a + \$a) / 2; // = 2.2360679774998

print "\$b<BR>";

print sqrt(5) . "<BR>"; // Actual PHP value = 2.2360679774998

// Difference
print bcSub(\$b, sqrt(5), 13);

Now it is accurate to 13 decimals on the second cycle!

If you started with 2 or 3 as the first approximation, you would still ultimately arrive at the same square root of 5 value by iteration.

The process really isn't difficult at all and it's easy to remember.

Starting with integers, the square root of any positive number may be computed rather quickly from scratch this way.

This process could also be modified for cube roots, 4th roots, etc.

In PHP it could be written more clearly as

\$NextApprox = ((\$x / \$CurrApprox) + \$CurrApprox) / 2;