Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get mathemical PI constant in Swift

Tags:

math

swift

darwin

People also ask

How do you declare pi constant?

In this program the value of π is defined in two different ways. One is by using using the preprocessor directive '#define' to make 'PI' equal to 3.142857. The other uses the key work 'const' to define a double called 'pi' equal to 22.0/7.0.

Is pi variable or constant?

The number π (/paɪ/; spelled out as "pi") is a mathematical constant that is the ratio of a circle's circumference to its diameter, approximately equal to 3.14159. The number π appears in many formulas across mathematics and physics.

Why pi is declared as a constant?

Pi is defined as the ratio of the circumference of any circle to its diameter. As all circles are similar and therefore proportional in dimensions, pi is therefore always the same for all circles and is a constant.


With Swift 3 & 4, pi is now defined as a static variable on the floating point number types Double, Float and CGFloat, so no specific imports are required any more:

Double.pi
Float.pi
CGFloat.pi

Also note that the actual type of .pi can be inferred by the compiler. So, in situations where it's clear from the context that you are using e.g. CGFloat, you can just use .pi (thanks to @Qbyte and @rickster for pointing that out in the comments).

For older versions of Swift:

M_PI is originally defined in Darwin but is also contained in Foundation and UIKit, so importing any of these will give you the right access.

import Darwin // or Foundation or UIKit

let pi = M_PI

Note: As noted in the comments, pi can also be used as unicode character in Swift, so you might as well do

let π = M_PI

alt + p is the shortcut (on US-keyboards) that will create the π unicode character.


import Darwin is not needed all M_x are visible with the import Foundation

( Xcode Version 6.4 (6E35b) )


warning: 'M_PI' is deprecated: Please use 'Double.pi' or '.pi' to get the value of correct type and avoid casting.

surprisingly, .pi also works fine. M_PI is deprecated as of Swift 4.2.1, Xcode 10.1, which is the current version I am using. SO, Use .pi, or Double.pi