r/dailyprogrammer • u/Elite6809 1 1 • Nov 29 '14
[2014-11-29] Challenge #190 [Practical Exercise] The Complex Number
(Practical Exercise): The Complex Number
The Friday challenge was not able to be submitted, so I'm going to deviate from the Friday standard here and do a submission which will benefit a different group of Daily Programmers. The vast majority of problems here are for computer scientists, and I feel this leaves out the rest of you - ie. those who are here more for the programming practice than the logical puzzles. Therefore, rather than being expected to solve a logic problem, you will be expected to implement a piece of software from a required specification, thus serving as an exercise in good programming practice and making use of language features available to you.
In this exercise you will implement functionality for complex numbers. (If your language already supports such functionality, pretend it doesn't exist.) Please note that this challenge is an object-oriented one. I apologise now to people who prefer procedural or functional languages, and I will try to make such an exercise in the future. Before you do this, let me introduce you to what a complex number is.
Background
The complex number system was created by mathematicians to more intuitively solve certain problems involving square roots. It has long been known that you cannot conventionally compute the square root of a negative number, as there is no number which, when multiplied by itself, will produce a negative number. If the original number is positive, the squared number will obviously also be positive. If the original number is negative, the squared number is also positive as multilplying two negative numbers together produces a positive number.
However, this meant that certain mathematical equations involving square roots had no solutions. This was quite an inconvenience for mathematicians at the time - it meant that certain polynomial equations could not be solved, as they ended up trying to work out the square root of a negative number. At some point, someone had the bright idea of ignoring the fact that you can't square root negatives. What if you pretended that the square root of -1 did exist? This is exactly what happened, and the value was defined as the imaginary unit, or i (imaginary as in the classical understanding of numbers, it doesn't actually exist). Therefore, i=√(-1). Using algebra this lets you square root other negative numbers as multiples of i, as √(ab) = √(a) * √(b).
√(-4) = √4 * √(-1) = √4 * i = 2 * i = 2i
√(-7) = √7 * √(-1) = √7 i
And so on. These numbers are called imaginary numbers. On their own they are useful, but they really come into their own when paired with normal numbera (aka real numbers, to distinguish them from imaginary numbers.) An example of a complex number would be 2+3i or 0.5-2.2i. These complex numbers are split into two bits, as you can see: the real component and the imaginary component. For example, given the complex number 3-7i, the real component is 3 and the imaginary component is -7i. Hence, a normal real number can be represented as a complex number with imaginary component 0i, like 2+0i.
Adding or subtracting two complex numbers is relatively simple. To do so, just add/subtract each component individually. For example, 1+3i add 3-2i equals 4+i. This requires no further explanation as there isn't much else to it.
Multiplying complex numbers is a bit more involved but still simple. Multiply the two complex numbers as you would an algebraic expression. For example, to multiply 1+3i and 3-2i, multiply each component together and add them all:
| 1 | 3i | |
|---|---|---|
| 3 | 3 | 9i |
| -2i | -2i | -6i2 |
Now, recall that i=√(-1). Hence, i2=-1. Therefore, -6i2=6. This means 1+3i multiplied by 3-2i equals 3+9i-2i+6, which is 9+7i.
To visualise it, you could plot these complex numbers on the number line. But wait... how would you do that? How can you represent the imaginary component on the number line without it floating somewhere above the line? In fact, that's essentially exactly what happens - an Argand diagram is used to do this. An Argand diagram representing the complex number 3-2i looks like this. This diagram can be used to compute a value of a complex number called the modulus, which is, is essence, the 'distance from zero' on the diagram - ie. the length of the grey line, which can be computed with Pythagoras' theorem. In this case, the modulus is √(32+(-2)2), which is √13.
Finally, there is another value of complex numbers, that is easy to work out. To work out the complex conjugate of a complex number, simply invert the sign of the imaginary component. For example, the complex conjugate of 3-2i is 3+2i. Simple.
Specification
You are to implement a class representing a complex number.
It is to be represented by floating-point number fields for the Real and Imaginary components.
It is to expose a method
GetModuluswhich returns a floating point number representing the modulus of the complex number.It is to expose a method
GetConjugatewhich returns another Complex number representing the complex conjugate.It is to have 3 static/shared/classifier methods, each taking 2 parameters, for the 3 operations
Add,SubtractandMultiply, each performing its respective operation and returning a Complex with the result of the operation.It is to expose a method
ToStringwhich converts the complex number to its string representation correctly: eg."3-2i","1-i"or"13".
The UML diagram for the Complex class looks like this.
Extension
If you are feeling up to it, implement these, too:
It is to expose a method
GetArgumentwhich returns a floating point angle, in radians, representing the argument of the complex number.It is to have another static method taking 2 parameters for the operation
Divide, which divides two complex numbers.
The UML diagram for the extended Complex class looks like this.
Making Use of your Language
The main challenge of this exercise is knowing your language and its features, and adapting your solution to them. For example, in Ruby, you would not write a ToString method - you would write a to_s method, as that is the standard in Ruby. In C++ and C#, you would not write static Add, Multiply methods. You would instead overload the +, -, *, / operators, and rather than writing a GetModulus method you would write a Modulus property. Knowing and using these features that programming language provide is an important part of software development.
You should also be writing clean, legible code. Follow the style guide for your language, and use the correct naming/capitalisation conventions, which differ from language to language.
5
u/Elite6809 1 1 Nov 29 '14
my solution in C#: https://gist.github.com/Quackmatic/47eaa947ddbb611d52bb
I've overloaded a lot of operators to make its usage more natural in conjunction with normal
doubles.5
u/dna42zz9 Nov 30 '14
My C++ solution
I decided to overload << for easier outputting.
I'm in my first programming class right now, so I'd appreciate any feedback!
10
u/jringstad Nov 29 '14
"The complex number system was designed to work around an inconsistency in mathematics regarding square-roots."
Uh... that is about as poorly worded as it could be.
3
u/dangerbird2 Nov 29 '14 edited Nov 29 '14
UML diagrams are for schmutzs!: here's my answer in Scheme
EDIT: To make it clear I'm using object-oriented design and not some hippy-SICP procedural Lisping, I've utilized Gambit Scheme's (non-standard) record type macros to give my complex type a proper method dispatch table. Also, added some comments to clarify what I'm doing
Expample of usage:
1
u/mpatraw Nov 30 '14
My solution using GForth (doesn't have complex>string yet): https://gist.github.com/mpatraw/4e9a7b6fdc5ef8b8a4d2
And here is the ideone link for testing it: http://ideone.com/rgXXRG
1
u/[deleted] Dec 01 '14
My Solution in C#, nothing more to say to it.
1
u/TieSoul 0 1 Jan 06 '15 edited Jan 06 '15
Cotton, a language I am developing (not a serious language, just for practice and fun.) Sorry about there not being any documentation/specification, but I'll do that when Cotton's more complete.
Couldn't do argument, because inverse trigonometric functions are not implemented in Cotton (and Cotton doesn't have access to the processor's trigonometric functions.)
complex.cn
Here's some testing in the REPL:
3
u/-Robbie Nov 29 '14
Haskell
abs is used for modulus
2
u/eslag90 Nov 29 '14
Python 2.7
Output:
2
u/thatrandomusername Nov 30 '14
my solution in javascript
2
u/chunes 1 2 Nov 30 '14 edited Nov 30 '14
Java:
I like this challenge. I'd love to see more challenges like this.
Example output:
2
u/bluelite Nov 30 '14 edited Nov 30 '14
Standard ML
It's been a while since I've done anything in SML. I've become rusty. Even though it's a functional language,
structuredefinitions give you something class-like.Sample usage:
2
u/logicalish Nov 29 '14 edited Nov 29 '14
Here's my solution in Python2/3, with the extra methods and python-specific constructs:
1
u/rectal_smasher_2000 1 1 Nov 29 '14
c++ (haven't tested thoroughly, might be buggy)
output:
1
u/rakomwolvesbane Nov 29 '14
Ruby solution with extension:
1
u/addaone Nov 29 '14
Ruby: https://github.com/snickroger/dailyprogrammer/blob/master/ruby/190h.rb
1
u/[deleted] Nov 30 '14 edited Dec 22 '18
deleted 0.1187 What is ^^^this?
1
u/jeaton Nov 30 '14
C++
1
u/10F1 Nov 30 '14
Go
http://play.golang.org/p/tmfDFpUSSA
1
u/jnazario 2 0 Nov 30 '14
broke it out in F# without the aid of coffee yet. note that DotNet has native support in System.Numerics.Complex, so this is just a crude approximation.
1
u/ddsnowboard Nov 30 '14
Solution in Java, with extension. I'd like to see more challenges like this one.
}
1
u/Judde10 Dec 01 '14
Clojure. New to the language, so any tips for readability would be appreciated.
1
u/DanTheProgrammingMan Dec 02 '14 edited Dec 02 '14
Ruby:
1
u/Maping Dec 03 '14
In Java, including the bonus:
1
u/[deleted] Dec 06 '14
Lua, with a bonus.
1
u/manlycoffee Dec 08 '14
My solution in JavaScript: https://gist.github.com/shovon/cd93c2e3a7189661b53e
The convention seems to be that--by de facto--the first letter of method names use a lowercase letter, where as constructor names start with a capital letter. Also, it seems camel case is the preferred naming convention in JavaScript.
Since JavaScript does not have any private member variables for its "classes", there seems to be two conventions used for introducing "privacy" of variables: prepend an underscore to the variable name, or use closures. The above solution uses the former.
Although, with the closure method, we do get inaccessible member variables, however, we end up with the issue that entirely new functions will be created for every new instances of the
Complexclass initialized. As a result, we get an increased memory overhead.And also, complex numbers are not just computed once and then discarded afterwards; large arrays of them will be created! One primary example is the Discrete Fourier Transform, where the result of applying this to a set of numbers yields an array of complex numbers. Hence why I used the underscore style to denote privacy.
Note: the use of underscores do not impose privacy at compilation level. It just tells other developers simply not to access those variables from outside of the class.
A side benefit of using the underscore style: much easier to peek into an object and see the status of its internal private member variables.
Either ways, if curious, here's an example of the closure technique: https://gist.github.com/shovon/a10d4b38b0a90dab04f1
1
u/hameerabbasi Dec 09 '14
My C# code
1
u/Nubtom Jan 11 '15 edited Jan 12 '15
This one's written in Java, I think. :D
1
u/[deleted] Feb 24 '15
Simple straight-forward solution in Python, using standard numeric methods for most operations.
0
u/[deleted] Nov 29 '14 edited Jan 02 '16
0
u/Godspiral 3 3 Nov 29 '14
J supports complex numbers natively. Conjugate is monad +, and modulus is magnitude |
J also supports classes/OOP, but just like making a class for points drives me to screaming, so would an oop approach for what is essentially just a pair of parameters. The reason oop is clumsy is that you may generate a pair in many ways, and then use parts of those pairs in other ways later. Getting them in and out of an object is annoying and useless.
in J as pairs,
addcomplex =: + NB. + works on pairs normally
1 3 + 3 _2
4 1
multcomplex =: (({.-{:) , [: +/ 1 2&{)@:([: , */)
1 3 multcomplex 3 _2
9 7
-8
u/Steve132 0 1 Nov 29 '14
Python cheating
C++ cheating