How can PHP be used to calculate trigonometric functions like sine and cosine with arbitrary precision?

When dealing with trigonometric functions like sine and cosine in PHP, the built-in functions such as sin() and cos() operate with limited precision. To calculate these functions with arbitrary precision, you can use the bcmath extension in PHP, which provides arbitrary precision decimal arithmetic. By using bcmath functions like bcadd(), bcmul(), and bcpow(), you can perform accurate calculations for trigonometric functions with the desired precision.

// Set the scale for bcmath calculations
ini_set('bcmath.scale', 20);

// Function to calculate sine with arbitrary precision
function bcsin($x) {
    $result = '0';
    for ($n = 0; $n < 10; $n++) {
        $result = bcadd($result, bcdiv(bcpow('-1', $n), bcfact(2*$n+1), 20) * bcpow($x, 2*$n+1), 20);
    }
    return $result;
}

// Function to calculate cosine with arbitrary precision
function bccos($x) {
    $result = '0';
    for ($n = 0; $n < 10; $n++) {
        $result = bcadd($result, bcdiv(bcpow('-1', $n), bcfact(2*$n), 20) * bcpow($x, 2*$n), 20);
    }
    return $result;
}

// Function to calculate factorial
function bcfact($n) {
    if ($n == 0) {
        return '1';
    }
    return bcmul($n, bcfact($n-1), 20);
}

// Example usage
$angle = '1.23456789';
$sin = bcsin($angle);
$cos = bccos($angle);

echo "Sine of $angle: $sin\n";
echo "Cosine of $angle: $cos\n";