Vyoms OneStopTesting.com - Testing EBooks, Tutorials, Articles, Jobs, Training Institutes etc.
OneStopGate.com - Gate EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
OneStopMBA.com - MBA EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
OneStopIAS.com - IAS EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
OneStopSAP.com - SAP EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
OneStopGRE.com - of GRE EBooks, Tutorials, Articles, FAQs, Jobs, Training Institutes etc.
Bookmark and Share Rss Feeds

Using the Complex type to solve Quadratic Equations | Articles | Recent Articles | News Article | Interesting Articles | Technology Articles | Articles On Education | Articles On Corporate | Company Articles | College Articles | Articles on Recession
Sponsored Ads
Hot Jobs
Fresher Jobs
Experienced Jobs
Government Jobs
Walkin Jobs
Placement Section
Company Profiles
Interview Questions
Placement Papers
Resources @ VYOMS
Companies In India
Consultants In India
Colleges In India
Exams In India
Latest Results
Notifications In India
Call Centers In India
Training Institutes In India
Job Communities In India
Courses In India
Jobs by Keyskills
Jobs by Functional Areas
Learn @ VYOMS
GATE Preparation
GRE Preparation
GMAT Preparation
IAS Preparation
SAP Preparation
Testing Preparation
MBA Preparation
News @ VYOMS
Freshers News
Job Articles
Latest News
India News Network
Interview Ebook
Get 30,000+ Interview Questions & Answers in an eBook.
Interview Success Kit - Get Success in Job Interviews
  • 30,000+ Interview Questions
  • Most Questions Answered
  • 5 FREE Bonuses
  • Free Upgrades

VYOMS TOP EMPLOYERS

Wipro Technologies
Tata Consultancy Services
Accenture
IBM
Satyam
Genpact
Cognizant Technologies

Home » Articles » Using the Complex type to solve Quadratic Equations

Using the Complex type to solve Quadratic Equations








Article Posted On Date : Thursday, March 22, 2012


Using the Complex type to solve Quadratic Equations
Advertisements

Introduction

One of the more interesting types introduced in .NET Framework 4.0 is the Complex structure which models the mathematical entity known as a 'complex number'. This is a number of the form a + bi where i represents the square root of -1.

The Complex structure lives in the System.Numerics namespace and, to use it, you need to add a reference to System.Numerics.dll to your project.

The implementation is reasonably complete with the standard arithmetic operators (+, -, *, /) being overloaded to work with complex numbers and there are implicit conversions from all the standard arithmetic types (int, long, double etc.). Construction using polar co-ordinates is supported and there is also a full set of mathematical functions defined on complex numbers such as trigonometric, absolute value, conjugate, reciprocal, power and square root.

So how can we use this type to solve a quadratic equation?

Solving quadratic equations (a first attempt)

One of the reasons why complex numbers were introduced into mathematics in the first place is so that the quadratic equation:

ax^2 + bx + c = 0 // where a, b and c are real numbers, a is non-zero and ^ denotes the power function.

always has a solution and, indeed, exactly two solutions or roots as they are called. For example, the equation:

x^2 + 4 = 0

has no real roots but it does have the complex roots 2i and -2i.

In general, the roots of any quadratic equation can be found from the formulas:

(-b + Sqrt (b^2- 4ac))/ 2a  and  (-b - Sqrt (b^2 - 4ac))/ 2a

It can be seen from these formulas that if b^2 - 4ac (known as the discriminant) is negative then the roots will be complex rather than real numbers

So, on the face of it, we should be able to solve such equations with the following C# program:

using System;
using System.Numerics;

class Test
{
    static void Main()
    {
        // as an example let's solve x^2 + 4 = 0
        Tuple<Complex, Complex> roots = SolveQuadratic(1, 0, 4);
        Console.WriteLine("The roots are {0} and {1}", roots.Item1, roots.Item2);
        Console.ReadKey();
    }

    static Tuple<Complex, Complex> SolveQuadratic(double a, double b, double c)
    {
        if (a == 0) throw new ArgumentException("The coefficient of x squared can't be zero");
        double discriminant = b * b - 4.0 * a * c;
        Complex temp = Complex.Sqrt(discriminant);
        Complex root1 = (-b + temp) / (2.0 * a);
        Complex root2 = (-b - temp) / (2.0 * a);
        return Tuple.Create(root1, root2);
    }
}

Notice that we're using the generic Tuple class which is another new feature of .NET 4.0. This enables us to return multiple values from a method without the need for 'out' parameters or defining a custom type.

However, when we examine the output of this program, we see two problems:

The roots are (1.22460635382238E-16, 2) and (-1.22460635382238E-16, -2)

Firstly, the roots have a tiny real component and secondly the output is expressed in Cartesian form (like points on the plane) and not in the more familiar a + bi format.

So what can we do about these problems?

Solving quadratic equations (an improved version)

Clearly, the first problem is caused by the Complex.Sqrt method producing anomalous results. The obvious way to solve this is to use the Math.Sqrt method instead and, if the discriminant is negative, multiply the result by the square root of -1.

As far as I can see, there is no support for the a + bi format in the Complex.ToString method or anywhere else so we need to write a custom method to deal with this. This gives us the following improved version of the program:

using System;
using System.Numerics;

class Test
{
    static void Main()
    {
        // as an example let's solve x^2 + 4 = 0
        Tuple<Complex, Complex> roots = SolveQuadratic(1, 0, 4);
        Console.WriteLine("The roots are {0} and {1}", ShowComplex(roots.Item1), ShowComplex(roots.Item2));

        // and also x^2 - 2x + 2
        roots = SolveQuadratic(1, -2, 2);
        Console.WriteLine("The roots are {0} and {1}", ShowComplex(roots.Item1), ShowComplex(roots.Item2));
        Console.ReadKey();
    }

    static Tuple<Complex, Complex> SolveQuadratic(double a, double b, double c)
    {
        if (a == 0) throw new ArgumentException("The coefficient of x squared can't be zero");
        double discriminant = b * b - 4.0 * a * c;
        Complex temp;
        if (discriminant >= 0)
        {
            temp = new Complex(Math.Sqrt(discriminant), 0);
        }
        else
        {
            temp = new Complex(0, Math.Sqrt(-discriminant));
        }
        Complex root1 = (-b + temp) / (2.0 * a);
        Complex root2 = (-b - temp) / (2.0 * a);
        return Tuple.Create(root1, root2);
    }

    static string ShowComplex(Complex c)
    {
        if (c == Complex.Zero) return "0";
        if (c.Imaginary == 0.0) return c.Real.ToString();
        string imag;
        if (c.Imaginary == 1)
            imag = "i";
        else if (c.Imaginary == -1)
            imag = "-i";
        else
            imag = c.Imaginary.ToString() + "i";
        if (c.Real == 0.0) return imag;
        string sep = (c.Imaginary > 0.0) ? "+" : "";
        return c.Real.ToString() + sep + imag;
    }
}

The output is now as expected:

The roots are 2i and -2i
The roots are 1+i and 1-i 






Sponsored Ads



Interview Questions
HR Interview Questions
Testing Interview Questions
SAP Interview Questions
Business Intelligence Interview Questions
Call Center Interview Questions

Databases

Clipper Interview Questions
DBA Interview Questions
Firebird Interview Questions
Hierarchical Interview Questions
Informix Interview Questions
Microsoft Access Interview Questions
MS SqlServer Interview Questions
MYSQL Interview Questions
Network Interview Questions
Object Relational Interview Questions
PL/SQL Interview Questions
PostgreSQL Interview Questions
Progress Interview Questions
Relational Interview Questions
SQL Interview Questions
SQL Server Interview Questions
Stored Procedures Interview Questions
Sybase Interview Questions
Teradata Interview Questions

Microsof Technologies

.Net Database Interview Questions
.Net Deployement Interview Questions
ADO.NET Interview Questions
ADO.NET 2.0 Interview Questions
Architecture Interview Questions
ASP Interview Questions
ASP.NET Interview Questions
ASP.NET 2.0 Interview Questions
C# Interview Questions
Csharp Interview Questions
DataGrid Interview Questions
DotNet Interview Questions
Microsoft Basics Interview Questions
Microsoft.NET Interview Questions
Microsoft.NET 2.0 Interview Questions
Share Point Interview Questions
Silverlight Interview Questions
VB.NET Interview Questions
VC++ Interview Questions
Visual Basic Interview Questions

Java / J2EE

Applet Interview Questions
Core Java Interview Questions
Eclipse Interview Questions
EJB Interview Questions
Hibernate Interview Questions
J2ME Interview Questions
J2SE Interview Questions
Java Interview Questions
Java Beans Interview Questions
Java Patterns Interview Questions
Java Security Interview Questions
Java Swing Interview Questions
JBOSS Interview Questions
JDBC Interview Questions
JMS Interview Questions
JSF Interview Questions
JSP Interview Questions
RMI Interview Questions
Servlet Interview Questions
Socket Programming Interview Questions
Springs Interview Questions
Struts Interview Questions
Web Sphere Interview Questions

Programming Languages

C Interview Questions
C++ Interview Questions
CGI Interview Questions
Delphi Interview Questions
Fortran Interview Questions
ILU Interview Questions
LISP Interview Questions
Pascal Interview Questions
Perl Interview Questions
PHP Interview Questions
Ruby Interview Questions
Signature Interview Questions
UML Interview Questions
VBA Interview Questions
Windows Interview Questions
Mainframe Interview Questions


Copyright © 2001-2024 Vyoms.com. All Rights Reserved. Home | About Us | Advertise With Vyoms.com | Jobs | Contact Us | Feedback | Link to Us | Privacy Policy | Terms & Conditions
Placement Papers | Get Your Free Website | IAS Preparation | C++ Interview Questions | C Interview Questions | Report a Bug | Romantic Shayari | CAT 2024

Fresher Jobs | Experienced Jobs | Government Jobs | Walkin Jobs | Company Profiles | Interview Questions | Placement Papers | Companies In India | Consultants In India | Colleges In India | Exams In India | Latest Results | Notifications In India | Call Centers In India | Training Institutes In India | Job Communities In India | Courses In India | Jobs by Keyskills | Jobs by Functional Areas

Testing Articles | Testing Books | Testing Certifications | Testing FAQs | Testing Downloads | Testing Interview Questions | Testing Jobs | Testing Training Institutes

Gate Articles | Gate Books | Gate Colleges | Gate Downloads | Gate Faqs | Gate Jobs | Gate News | Gate Sample Papers | Gate Training Institutes

MBA Articles | MBA Books | MBA Case Studies | MBA Business Schools | MBA Current Affairs | MBA Downloads | MBA Events | MBA Notifications | MBA FAQs | MBA Jobs
MBA Job Consultants | MBA News | MBA Results | MBA Courses | MBA Sample Papers | MBA Interview Questions | MBA Training Institutes

GRE Articles | GRE Books | GRE Colleges | GRE Downloads | GRE Events | GRE FAQs | GRE News | GRE Training Institutes | GRE Sample Papers

IAS Articles | IAS Books | IAS Current Affairs | IAS Downloads | IAS Events | IAS FAQs | IAS News | IAS Notifications | IAS UPSC Jobs | IAS Previous Question Papers
IAS Results | IAS Sample Papers | IAS Interview Questions | IAS Training Institutes | IAS Toppers Interview

SAP Articles | SAP Books | SAP Certifications | SAP Companies | SAP Study Materials | SAP Events | SAP FAQs | SAP Jobs | SAP Job Consultants
SAP Links | SAP News | SAP Sample Papers | SAP Interview Questions | SAP Training Institutes |


Copyright ©2001-2024 Vyoms.com, All Rights Reserved.
Disclaimer: VYOMS.com has taken all reasonable steps to ensure that information on this site is authentic. Applicants are advised to research bonafides of advertisers independently. VYOMS.com shall not have any responsibility in this regard.