1

I forked a project from Github, Xcode shows a lot of warnings:

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

and

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

Since both M_PI and M_PI_2 are prompted to be replaced by Double.pi, I assume there are in fact the same value. However, there's this code in the project:

switch angle {

    case M_PI_2:
        ...

    case M_PI:
        ...

    case Double.pi * 3:
        ...

    default:
        ...

}

I'm really confused here, are M_PI and M_PI_2 different? or are they just the same?

UPDATE:

It turns out to be my blunder, Xcode says 'M_PI_2' is deprecated: Please use Double.pi / 2 or .pi / 2 to get the value of correct type and avoid casting. so it isn't a bug, just too hard to notice the difference of 2 prompts.

Nilanshu Jaiswal
  • 1,583
  • 3
  • 23
  • 34
Bright
  • 5,699
  • 2
  • 50
  • 72

3 Answers3

16

Use Double.pi / 2 for M_PI_2 and Double.pi for M_PI.

You can also use Float.pi and CGFloat.pi.

In Swift 3 & 4, pi is defined as a static variable on the floating point number types Double, Float and CGFloat.

Nilanshu Jaiswal
  • 1,583
  • 3
  • 23
  • 34
harshal jadhav
  • 5,456
  • 2
  • 18
  • 26
0

M_PI is defined as a macro

#define M_PI   3.14159265358979323846264338327950288

in math.h and part of the POSIX standard.

Follow This You can find reference answer here

Check This Solution - How you can use it

Pang
  • 9,564
  • 146
  • 81
  • 122
Nilesh Mahajan
  • 607
  • 4
  • 16
0

These constants are related to the implementations of different functions in the math library:

s_cacos.c:  __real__ res = (double) M_PI_2 - __real__ y;
s_cacosf.c:  __real__ res = (float) M_PI_2 - __real__ y;
s_cacosh.c:                    ? M_PI - M_PI_4 : M_PI_4)
...
s_clogf.c:      __imag__ result = signbit (__real__ x) ? M_PI : 0.0;

M_PI, M_PI_2, and M_PI_4 show up quite often but there's no 2.0 * M_PI. 2π is just not that useful, at least in implementing libm.

M_PI_2 and M_PI_4, their existences are well justified. The documentation of the GNU C library suggests that "these constants come from the Unix98 standard and were also available in 4.4BSD". Compilers were not that smart back at that time. Typing M_PI/4 instead of M_PI_4 may cause an unnecessary division. Although modern compilers can optimize that away (GCC uses mpfr since 2008 so even rounding is done correctly), using numeric constants is still a more portable way to write high-performance code.

Jogendar Choudhary
  • 3,476
  • 1
  • 12
  • 26