<< Back to SWIFT
Swift Math: abs, sqrt and pow
Use math methods. Call abs, max, min, sqrt, floor, ceil and pow.Math. Algorithms often change numbers in specific ways. An array index is always positive. With abs we take an absolute value. This can be used as an index.
Funcs like sqrt are less often used. But when floor() or ceil() is needed, they simplify our Swift code. With Pow we apply exponents.
Abs. Let us begin with abs(). This method takes an absolute value. It always returns a positive number. It converts negative values to positive ones.
And: It returns positive numbers unchanged. With abs we can convert any number into a possible array index (as for hashing).
Tip: Abs is often used in lower-level code. For most dictionary lookups, we do not need to implement a hash computation.
Swift program that uses abs
let number = -10
print(number)
// Use abs to make number positive.
let result = abs(number)
print(result)
// An absolute value is always positive.
let result2 = abs(result)
print(result2)
Output
-10
10
10
Max, min. Sometimes in a for-loop we want to iterate until we reach the higher, or lower, of two values. This creates a safe boundary for the loop.
Max: This returns the larger of two numbers. It handles negative numbers. Here it returns 2000 because that was the larger argument.
Min: Returns the smaller of two numbers. In this example we get 10 because 2000 is larger than 10.
Swift program that uses max, min
let small = 10
let big = 2000
// Compute max.
let resultMax = max(small, big)
print(resultMax)
// Compute min.
let resultMin = min(small, big)
print(resultMin)
Output
2000
10
Sqrt. This method is part of Foundation. It requires a Double argument. So we must cast Ints that we want to take the square roots of.
Note: Taking a square root is not a common requirement in most programs. So including Foundation is not a big problem.
Swift program that uses sqrt method
import Foundation
// Compute square root with Foundation.
let result = sqrt(Double(25))
print(result)
Output
5.0
Floor. This is a common mathematical function. It removes the fractional part of a number. So it changes 1.1 to 1.0. It will change 1.9 to 1.0 as well.
Swift program that uses floor method
import Foundation
// Compute floor for a Double.
let number1 = 1.1
let floor1 = floor(number1)
print("floor \(number1) = \(floor1)")
// Floor removes the fractional part.
let number2 = 1.9
let floor2 = floor(number2)
print("floor \(number2) = \(floor2)")
Output
floor 1.1 = 1.0
floor 1.9 = 1.0
Ceil. This method rounds numbers up, discarding a fractional part. So the ceiling of 0.1 is 1. Ceil is part of Foundation, so we must include the import statement.
Swift program that uses ceil method
import Foundation
let number = 0.1
print(number)
// Use ceil to remove the fractional part and round up.
let result = ceil(number)
print(result)
Output
0.1
1.0
Pow. This method takes exponents. It is part of Foundation. It requires a Double and then returns a Double. Here we take the square of 3.0 for a result of 9.0.
Swift program that uses pow method
import Foundation
// Use power of 2 on 3 (square it).
let number = 3.0
let result = pow(number, 2)
// Write results.
print("\(number) squared = \(result)")
Output
3.0 squared = 9.0
Sign. This property returns a plus or minus value. If the Double is negative, sign returns minus. If it is positive, the result is plus.
Tip: To test an Int with sign(), we must use a cast to a Double value. No Int-accepting overload exists.
Swift program that uses signbit
import Foundation
// A negative number has a sign of minus.
let number = -1.0
let result = number.sign
print("\(number), \(result)")
// Convert Int to Double to use sign.
// ... Positive numbers have sign bits of plus.
let number2 = 200
let result2 = Double(number2).sign
print("\(number2), \(result2)")
Output
-1.0, minus
200, plus
Odd, even. With a modulo division, we can determine if a number is even or odd. We must take special care on negative numbers. We can place this logic in funcs.
Odd, Even
Fibonacci. In the Fibonacci sequence, each number is equal to the sum of the two previous numbers. This sequence builds on itself. And it is found throughout nature.
Fibonacci
A review. Numbers are everywhere in our universe, even if unseen. With these math funcs in Swift, we manipulate numbers in known and common ways. This simplifies many programs.
Related Links:
- Swift String Append Example: reserveCapacity
- Swift File (Read Text File Into String)
- Swift Find Strings: range of Example
- Swift Subscript Example
- Swift hasPrefix and hasSuffix Examples
- Swift Array of Dictionary Elements
- Swift Tutorial
- Swift Odd and Even Numbers
- Swift Operator: Equality, Prefix and Postfix
- Swift Dictionary Examples
- Swift Class Example: init, self
- Swift Combine Arrays: append, contentsOf
- Swift Initialize Array
- Swift Int Examples: Int.max, Int.min
- Swift 2D Array Examples
- Swift Error Handling: try, catch
- Swift Repeat While Loop
- Swift Optional: Nil Examples
- Swift Replace String Example
- Swift Print: Lines, Separator and Terminator
- Swift inout Keyword: Func Example
- Swift Lower, Uppercase and Capitalized Strings
- Swift enum Examples: case, rawValue
- Swift Padding String Example (toLength)
- Swift UIActivityIndicatorView Example
- Swift UIAlertController: Message Box, Dialog Example
- Swift UIButton, iOS Example
- Swift UICollectionView Tutorial
- Swift UIColor iOS Example: backgroundColor, textColor
- Swift UIFont Example: Name and Size
- Swift UIImageView Example
- Swift UIKit (Index)
- Swift UILabel Tutorial: iPhone App, Uses ViewController
- Swift String
- Swift Remove Duplicates From Array
- Swift If, If Else Example
- Swift Caesar Cipher
- Swift UIStepper Usage
- Swift UISwitch: ViewController
- Swift UITableView Example: UITableViewDataSource
- Swift UITextField: iPhone Text Field Example
- Swift UITextView Example
- Swift UIToolbar Tutorial: UIBarButtonItem
- Swift UIWebView: LoadHtmlString Example
- Swift Var Versus Let Keywords
- Swift Math: abs, sqrt and pow
- Swift Reverse String
- Swift Struct (Class Versus Struct)
- Top 22 Swift Interview Questions (2021)
- Swift Substring Examples
- Swift Switch Statements
- Swift Convert Int to Character: UnicodeScalar, utf8
- Swift Property Examples
- Swift isEmpty String (characters.count Is Zero)
- Swift Recursion
- Swift ROT13 Func
- Swift Convert String to Byte Array: utf8 and UInt8
- Swift Keywords
- Swift Convert String to Int Example
- Swift Join Strings: joined, separator Examples
- Swift String Literal, Interpolation
- Swift Extension Methods: String, Int Extensions
- Swift Characters: String Examples
- Swift Func Examples: Var, Return and Static
- Swift Guard Example: Guard Else, Return
- Swift Fibonacci Numbers
- Swift Trim Strings
- Swift Set Collection: Insert and Contains
- Swift Tuple Examples
- Swift Loops: for, repeat and while Examples
- Swift Split Strings Example (components)
- Swift Array Examples, String Arrays
- Swift UIPickerView Example: UIPickerViewDataSource
- Swift UIProgressView Example: Progress
- Swift UISegmentedControl
- Swift UISlider Example
- Swift Random Numbers: arc4random
- Swift ASCII Table
- Swift Range Examples (index, offsetBy)
- Swift String Length
- Swift Sort String Arrays: Closure Examples
Related Links
Adjectives
Ado
Ai
Android
Angular
Antonyms
Apache
Articles
Asp
Autocad
Automata
Aws
Azure
Basic
Binary
Bitcoin
Blockchain
C
Cassandra
Change
Coa
Computer
Control
Cpp
Create
Creating
C-Sharp
Cyber
Daa
Data
Dbms
Deletion
Devops
Difference
Discrete
Es6
Ethical
Examples
Features
Firebase
Flutter
Fs
Git
Go
Hbase
History
Hive
Hiveql
How
Html
Idioms
Insertion
Installing
Ios
Java
Joomla
Js
Kafka
Kali
Laravel
Logical
Machine
Matlab
Matrix
Mongodb
Mysql
One
Opencv
Oracle
Ordering
Os
Pandas
Php
Pig
Pl
Postgresql
Powershell
Prepositions
Program
Python
React
Ruby
Scala
Selecting
Selenium
Sentence
Seo
Sharepoint
Software
Spellings
Spotting
Spring
Sql
Sqlite
Sqoop
Svn
Swift
Synonyms
Talend
Testng
Types
Uml
Unity
Vbnet
Verbal
Webdriver
What
Wpf