
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Print Absolute Value of Complex Numbers in Swift
In this article, we will learn how to write a swift program to print the absolute value of complex numbers. Complex numbers are those numbers which express in the form of x+yi, where x and y are real numbers and ?i' is an imaginary number known as iota. For example 4+2i, 6-4i, etc. Now the absolute value of the complex number is the positive square root of the sum of the squares of the real and the imaginary parts.
$\mathrm{|\:Absolute\:Value\:|\:=\:\sqrt{(real)^{2}\:+\:(img)^{2}}}$
For example ?
Complex number = 4 + 2i
$\mathrm{|\:Absolute\:Value\:|\:=\:\sqrt{(4)^{2}\:+\:(2)^{2}}}$
$\mathrm{=\:\sqrt{16 + 4}}$
$\mathrm{=\:\sqrt{20}}$
= 4.4721359549995
Algorithm
Step 1 ? Create a struct.
Step 2 ? Create two properties to store real and imaginary parts.
Step 3 ?Method to display the complex number
Step 4 ? Method to find the absolute value of the given complex number.
Step 5 ? Create and initialize the instance of the ComplexNumber struct.
Step 6 ? Access the methods of the struct using the dot operator.
Step 7 ? Print the output.
Example
Following the Swift program to print the absolute value of a complex numbers.
import Foundation import Glibc // Structure to create complex number struct ComplexNumber{ var real: Double var imaginary: Double // Method to display complex number func display(){ print("Complex number: \(real) + \(imaginary)i") } // Method to calculate absolute value of the // complex number func absolute() -> Double { return sqrt(real * real + imaginary * imaginary) } } // Initialize complex number let cNum = ComplexNumber(real: 5.0, imaginary: 6.0) cNum.display() print("Absolute Value:",cNum.absolute())
Output
Complex number: 5.0 + 6.0i Absolute Value: 7.810249675906654
Here in the above code, we create a struct which contains two properties to store real and imaginary parts of the complex number, a method to display complex numbers, and one more method to find the absolute value of the given complex number. In the absolute() function, we find the square root of the sum of the squares of the real and the imaginary parts using sqrt() function. Now we create an instance of the ComplexNumber structure and initialize the complex number. Using the instance along with the dot operator we access the absolute() function and display output.
Conclusion
Therefore, this is how we can find the absolute value of complex numbers. Absolute value is also known as the distance of the number from zero(in the line graph) and its value is always positive.