Swift Tutorial Swift Resources
Python Java C++ C C# PHP R SQL DS Algo InterviewQ

Swift - fdim() Function



The Swift fdim() function returns positive difference between x and y, if x > y, else returns zero. Mathematically, it can be expressed as:

fdim (x, y) = max (x-y, 0)

Syntax

In Foundation framework, it is defined as follows:

public func fdim(_ lhs: CGFloat, _ rhs: CGFloat) -> CGFloat
public func fdim(_ lhs: Float, _ rhs: Float) -> Float
public func fdim(_ lhs: Float80, _ rhs: Float80) -> Float80
public func fdim(_ __x: Double, _ __y: Double) -> Double

Parameters

x, lhs Specify the first value.
y, rhs Specify the second value.

Return Value

Returns the positive difference between x and y.

Example:

The example below shows the usage of fdim() function.

import Foundation

print("fdim(100.0, 50.0) = \(fdim(100.0, 50.0))")
print("fdim(50.0, -100.0) = \(fdim(50.0, -100.0))")
print("fdim(-50.0, 50.0) = \(fdim(-50.0, 50.0))")
print("fdim(-100.0, -50.0) = \(fdim(-100.0, -50.0))")

The output of the above code will be:

fdim(100.0, 50.0) = 50.0
fdim(50.0, -100.0) = 150.0
fdim(-50.0, 50.0) = 0.0
fdim(-100.0, -50.0) = 0.0

❮ Swift Math Functions

5