Skip to content

Instantly share code, notes, and snippets.

@DonaldKellett
Last active November 25, 2018 16:37
Show Gist options
  • Save DonaldKellett/babc192cce941e4e6e7b831e5f0c4ca9 to your computer and use it in GitHub Desktop.
Save DonaldKellett/babc192cce941e4e6e7b831e5f0c4ca9 to your computer and use it in GitHub Desktop.
A simple math function that computes the cardinal sine of a real number x. It computes the historical (unnormalized) cardinal sine by default, but if its second argument is set to SINC_NORMALIZED then it computes the normalized cardinal sine of x instead. A great complement to the math functions already available as part of the PHP Core.
<?php
/*
function.sinc.php
A simple math function (with input validation)
that computes the cardinal sine of a real
number $x
Author: Donald Leung
NOTE: Comes with two user-defined constants
*/
// Constants (for use by the sinc() function as flags)
define('SINC_DEFAULT', 0);
define('SINC_NORMALIZED', 1);
// Function declaration and definition
function sinc($x, $flag = SINC_DEFAULT) {
// Type check "x" - confirm that it is either of an integer or a float
if (!is_int($x) && !is_float($x)) throw new InvalidArgumentException('In sinc(), the first argument "x" passed in must either be an integer or a float');
// Validate the flag - it can only be one of SINC_DEFAULT and SINC_NORMALIZED
if ($flag !== SINC_DEFAULT && $flag !== SINC_NORMALIZED) throw new InvalidArgumentException('The sinc() function only accepts 2 possible flags: SINC_DEFAULT and SINC_NORMALIZED');
// Special Case: where x = 0, sinc(x) = sinc(0) = 1
if ($x == 0) return 1;
// If the flag is set to SINC_NORMALIZED then multiply the argument "x" by pi and compute its unnormalized cardinal sine at pi * x
if ($flag === SINC_NORMALIZED) return sinc(M_PI * $x);
// Otherwise just return the unnormalized cardinal sine of x
return sin($x) / $x;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment