|
exp
Calculates the exponent of e
(PHP 4, PHP 5)
Example 1146. exp() example<?php The above example will output: 1.6275E+005 Related Examples ( Source code ) » exp Examples ( Source code ) » File based login Examples ( Source code ) » Generating Tables from XML Examples ( Source code ) » Transforming XML into Basic HTML Examples ( Source code ) » Print all MySQL status value Examples ( Source code ) » Creating a Test Cookie Examples ( Source code ) » Clean Path by Regular Expressions Examples ( Source code ) » Read text file into array and output Examples ( Source code ) » Regular Expression validates an email adress Examples ( Source code ) » Email validation with Regular Expressions Examples ( Source code ) » Exp Examples ( Source code ) » Finding a Substring Within a String with strstr() Examples ( Source code ) » String replace with Regular Expressions Examples ( Source code ) » Use Reflection class to export class Examples ( Source code ) » For loop format Examples ( Source code ) » Shorthand Operators summary table Code Examples / Notes » expkonrad
working version (checked) of below code is <?php // see bccomp for this code (signed and unsigned zero!) function bccomp_zero($amount) { return bccomp($amount, (@$amount{0}=="-"?'-':'').'0.0'); } // arbitrary precision function (x^n)/(n)! function bcpowfact($x, $n) { if (bccomp_zero($n) == 0) return '1'; if (bccomp($n, '1') == 0) return $x; $a = $x; // 1st step: a *= x / 1 $i = $n; while (bccomp($i, '1') == 1) { // ith step: a *= x / i $a = bcmul($a, bcdiv($x, $i)); $i = bcsub($i, '1'); // bc idiom for $i-- } return $a; } // arbitrary precision exp() function function bcexp($x, $digits) { $sum = $prev_sum = '0.0'; $error = '0.'.str_repeat('0', $digits-1).'1'; // 0.1*10^-k $n = '0.0'; do { $prev_sum = $sum; $sum = bcadd($sum, bcpowfact($x, $n)); $n = bcadd($n, '1'); // bc idiom for $n++ } while (bccomp(bcsub($sum, $prev_sum), $error) == 1); return $sum; } ?> info
This only returns the first 51 digits after the decimal point.
boards
Note regarding the mathematical function exp(x): To continue accuracy of the exponential function to an infinite amount of decimal places, one would use the power series definition for exp(x). (in LaTeX form:) e^x = \sum_{n=0}^{\infty} \frac{x^n}{n!} So, to do that in PHP (using BC math): <?php // arbitrary precision function (x^n)/(n)! function bcpowfact($x, $n) { if (bccomp($n, '0') == 0) return '1.0'; if (bccomp($n, '1') == 1) return $x; $a = $x; // nth step: a *= x / 1 $i = $n; while (bccomp($i, '1') == 1) { // ith step: a *= x / i $a = bcmul($a, bcdiv($x, $i)); $i = bcsub($i, '1'); // bc idiom for $i-- } return $a; } // arbitrary precision exp() function function bcexp($x, $decimal_places) { $sum = $prev_sum = '0.0'; $error = bcdiv(bcpow('10', '-'.$decimal_places), 10); // 0.1*10^-k $n = '0'; do { $prev_sum = $sum; $sum = bcadd($sum, bcpowfact($x, $n)); } while (bccomp(bcsub($sum, $prev_sum), $error) == 1); return $sum; } ?> |