高中数学函数数

玩蛇网提供最新Python编程技术信息以及Python资源下载!
您现在的位置:
玩蛇网推荐图文教程:
在中,大家都已经了解了有很多运算符可以进行一些数学运算,但是要处理复杂的问题是不是所有都要自己一行一行的来编写呢?
提醒大家,这个时候,最先想到的就应该是有没有这样的内置库,math模块提供了很多特别的数学运算功能。
在很多数字运算中,我们都会用到一些特别的常量,例如 圆周率& (pi)和自然常数e,下面我们用math模块来输出圆周率& (pi)和自然常数e的值:
&&& import math
&圆周率& : %.30f&% math.pi&& #替换方法,取小数点后30位的值。
&&& print &自然常数e: %.30f& % math.e #方法同上,这里我们用print,在python函数体内我们要用来返回值。
输出结果:
圆周率& :& 3.468544
自然常数e: 2.298428
math模块处理正号和负号
&&& import math
&&& print math.fabs(-1.1)
&&& print math.fabs(-1.0)
输出结果:
另外,math模块还包含了一些其它的方法,下面只简单列出一些常用的:
1 )、math.ceil(i)& #这个方法对i向上取整,i = 1.3 ,返回值为2
2 )、math.floor(i)& #正好与上面相反,是向下取整。i = 1.4,返回1
3 )、math.pow(a, b)& # 返回a的b次方
4 )、math.sqrt(i)& #返回i的平方根
其它方法大家可以查看官方库文档,或者用系统命令 ,来查看更多方法和参数的一些规范。
玩蛇网文章,转载请注明出处和来源网址:
微信公众号搜索"玩蛇网Python之家"加关注,每日最新的Python资讯、图文视频教程可以让你一手全掌握。强烈推荐关注!
【微信扫描下图可直接关注】
玩蛇网PythonQQ群,欢迎加入: ①
出炉日期: 14:56
我要分享到:
评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
必知PYTHON教程Must Know PYTHON Tutorials
最新内容NEWS
相关文章RECOMMEND
Navigation
玩蛇网Python之家,简称玩蛇网,是一个致力于推广python编程技术、程序源码资源的个人网站。站长 斯巴达 是一位
长期关注 软件、互联网、服务器与各种开发技术的Python爱好者,建立本站旨在与更多朋友分享派森编程的乐趣!
本站团队成员:
欢迎加入团队...MSSQL SERVER 2005 数学函数整理
字体:[ ] 类型:转载 时间:
MSSQL SERVER 2005 数学函数整理
MSSQL SERVER 2005 数学函数 1.求绝对值 ABS() select FWeight-50,ABS(FWeight-50),ABS(-5.38) from T_Person 2.求幂 POWER(X,Y) 用来计算X的Y次幂 select FWeight,POWER(FWeight,-0.5),POWER(FWeight,2), POWER(FWeight,3),POWER(FWeight,4) from T_Person select Power(2,2) 3.求平方根 SQRT() select FWeight,SQRT(FWeight) from T_Person 4. 求随机数 RAND() 支持有参数,也可以没参数 select RAND() select RAND(123) 5.舍入到最大整数 CEILING() select FName,FWeight,CEILING(FWeight),CEILING(FWeight*-1) from T_Person 6.舍入到最小整数 FLOOR() select FName,FWeight,FLOOR(FWeight),FLOOR(FWeight*-1) from T_Person 7.四舍五入 ROUND() ROUND(m,d) m为待进行四舍五入的数值,d为计算精度,也就是四舍五入时保留的小数位数 d为0表示不保留小数位,d为负值表示在整数部分进行四舍五入。 select FName,FWeight,ROUND(FWeight,1),ROUND(FWeight*-1,0),ROUND(FWeight,-1) from T_Person 8.求正弦值 SIN() select FName,FWeight,SIN(FWeight)from T_Person 9.求余弦值 COS() select FName,FWeight,COS(FWeight) from T_Person 10.求反正弦 ASIN() select FName,FWeight,ASIN(1/FWeight) from T_Person 11.求反余弦 ACOS() select FName,FWeight,ACOS(1/FWeight) from T_Person 12.求正切值 TAN() select FName,FWeight,TAN(FWeight) from T_Person 13.求反正切值 ATAN() select FName,FWeight,ATAN(FWeight) from T_Person 14.求两个变量的反正切 ATN2(X,Y) 类似于计算Y/X的反正切 select FName,FWeight,ATN2(Fweight,2) from T_Person 15.求余切 COT() select FName,FWeight,COT(Fweight) from T_Person 16.求圆周率π值 PI() select FName,FWeight,Fweight*PI(),PI() from T_Person 17.弧度制转换为角度制 DEGREES() 结果的精确度与参数有关 select DEGREES(PI()),DEGREES(3.0),DEGREES(3) 18.角度制转换为弧度制 RADIANS() 结果的精确度与参数有关 select RADIANS(180),RADIANS(180.0) 19.求符号 SIGN() 返回一个数值的符号,如果数值大于0则返回1, 如果数值等于0则返回0,如果数值小于0则返回-1. 结果的精确度与参数有关 select FName,FWeight-48.68,SIGN(FWeight-48.68),SIGN(1),SIGN(1.000) from T_Person 20.求整除余数 % select FName,FWeight,FWeight%5 from T_Person 21.求自然对数 LOG() select FName,FWeight,LOG(FWeight),LOG(1.00) from T_Person 22.求以10为底的对数 LOG10() select FName,Fweight,LOG10(FWeight),LOG10(100) from T_Person ps: 主要参照《程序员的SQL金典》 实例有所改动。 T_Person表的创建
代码如下: create table T_Person ( FIdNumber varchar(20), FName varchar(20), FBirthDay datetime, FRegDay datetime, FWeight numeric(10,2), )
大家感兴趣的内容
12345678910
最近更新的内容
常用在线小工具Keyboard Shortcuts?
Next menu item
Previous menu item
Previous man page
Next man page
Scroll to bottom
Scroll to top
Goto homepage
Goto search(current page)
Focus search box
Change language:
Brazilian Portuguese
Chinese (Simplified)
BC 数学 函数
Table of Contents — 2个任意精度数字的加法计算 — 比较两个任意精度的数字 — 2个任意精度的数字除法计算 — 对一个任意精度数字取模 — 2个任意精度数字乘法计算 — 任意精度数字的成方 — Raise an arbitrary precision number to another, reduced by a specified modulus — 设置所有bc数学函数的默认小数点保留位数 — 任意精度数字的二次方根 — 2个任意精度数字的减法
Here are some useful functions to convert large hex numbers from and to large decimal ones :&?php& & public static function bchexdec($hex) {& & & & if(strlen($hex) == 1) {& & & & & & return hexdec($hex);& & & & } else {& & & & & & $remain = substr($hex, 0, -1);& & & & & & $last = substr($hex, -1);& & & & & & return bcadd(bcmul(16, bchexdec($remain)), hexdec($last));& & & & }& & }& & public static function bcdechex($dec) {& & & & $last = bcmod($dec, 16);& & & & $remain = bcdiv(bcsub($dec, $last), 16);& & & & if($remain == 0) {& & & & & & return dechex($last);& & & & } else {& & & & & & return bcdechex($remain).dechex($last);& & & & }& & }
Please be aware not to use/have spaces in your strings. It took me a while to find the error in some advanced calculations!&?phpecho bcadd("1", "2"); echo bcadd("1", "2 "); echo bcadd("1", " 2"); ?&
A good use for BCMath functions:The functions below can convert a number in any base (from 2 to 256) to its decimal value and vice-versa.// convert a decimal value to any other base valuefunction dec2base($dec,$base,$digits=FALSE) {& & if($base&2 or $base&256) die("Invalid Base: ".$base);& & bcscale(0);& & $value="";& & if(!$digits) $digits=digits($base);& & while($dec&$base-1) {& & & & $rest=bcmod($dec,$base);& & & & $dec=bcdiv($dec,$base);& & & & $value=$digits[$rest].$& & }& & $value=$digits[intval($dec)].$& & return (string) $}// convert another base value to its decimal valuefunction base2dec($value,$base,$digits=FALSE) {& & if($base&2 or $base&256) die("Invalid Base: ".$base);& & bcscale(0);& & if($base&37) $value=strtolower($value);& & if(!$digits) $digits=digits($base);& & $size=strlen($value);& & $dec="0";& & for($loop=0;$loop&$$loop++) {& & & & $element=strpos($digits,$value[$loop]);& & & & $power=bcpow($base,$size-$loop-1);& & & & $dec=bcadd($dec,bcmul($element,$power));& & }& & return (string) $}function digits($base) {& & if($base&64) {& & & & $digits="";& & & & for($loop=0;$loop&256;$loop++) {& & & & & & $digits.=chr($loop);& & & & }& & } else {& & & & $digits ="abcdefghijklmnopqrstuvwxyz";& & & & $digits.="ABCDEFGHIJKLMNOPQRSTUVWXYZ-_";& & }& & $digits=substr($digits,0,$base);& & return (string) $}The purpose of digits() function above is to supply the characters that will be used as digits for the base you want. NOTE: You can use any characters for that when you convert to another base, but when you convert again to the decimal base, you need to use the same characters or you will get another unexpected result.
I wrote this function with many BCMath functions. It should be the fastest function in PHP to find the number pi into any precision, my test is it generate 2000 digits after the dot in 8 seconds. I don't think you need anything more than that.&?phpfunction bcpi($precision){& & $limit = ceil(log($precision)/log(2))-1;& & bcscale($precision+6);& & $a = 1;& & $b = bcdiv(1,bcsqrt(2));& & $t = 1/4;& & $p = 1;& & while($n & $limit){& & & & $x = bcdiv(bcadd($a,$b),2);& & & & $y = bcsqrt(bcmul($a, $b));& & & & $t = bcsub($t, bcmul($p,bcpow(bcsub($a,$x),2)));& & & & $a = $x;& & & & $b = $y;& & & & $p = bcmul(2,$p);& & & & ++$n;& & }& & return bcdiv(bcpow(bcadd($a, $b),2),bcmul(4,$t),$precision);}?&
Some useful bcmath functions:&?phpfunction bcfact($fact, $scale = 100){& & if($fact == 1) return 1;& & return bcmul($fact, bcfact(bcsub($fact, '1'), $scale), $scale);}function bcexp($x, $iters = 7, $scale = 100){& & $res = bcadd('1.0', $x, $scale);& & for($i = 0; $i & $iters; $i++)& & {& & & & $res += bcdiv(bcpow($x, bcadd($i, '2'), $scale), bcfact(bcadd($i, '2'), $scale), $scale);& & }& & return $res;}function bcln($a, $iters = 10, $scale = 100) { & & $result = "0.0"; & & & & for($i = 0; $i & $iters; $i++) & & {& & & & $pow = bcadd("1.0", bcmul($i, "2.0", $scale), $scale);& & & & $mul = bcdiv("1.0", $pow, $scale); & & & & $fraction = bcmul($mul, bcpow(bcdiv(bcsub($a, "1.0", $scale), bcadd($a, "1.0", $scale), $scale), $pow, $scale), $scale); & & & & $result = bcadd($fraction, $result, $scale); & & } & & & & $res = bcmul("2.0", $result, $scale); & & return $res;} function bcpowx($a, $b, $iters = 25, $scale = 100){& & $ln = bcln($a, $iters, $scale);& & return bcexp(bcmul($ln, $b, $scale), $iters, $scale);}$precision = 35;echo "3^4.5,& & & & & precision 15, iters 25 = " . bcpowx('3', '4.5', 25, $precision) . "\n";echo "4.5^3,& & & & & precision 15, iters 25 = " . bcpowx('4.5', '3', 25, $precision) . "\n";echo "8^1/2,& & & & & precision 15, iters 25 = " . bcpowx('8', '0.5', 25, $precision) . "\n";echo "28^-1,& & & & & precision 15, iters 25 = " . bcpowx('28', '-1', 25, $precision) . "\n";echo "432^0,& & & & & precision 15, iters 25 = " . bcpowx('432', '0', 25, $precision) . "\n";echo "0^0,& & & & & & precision 15, iters 25 = " . bcpowx('0.0', '0', 25, $precision) . "\n";echo "9^999,& & & & & precision 15, iters 25 = " . bcpowx('9', '999', 25, $precision) . "\n";echo "9^9999,& & & && precision 15, iters 25 = " . bcpowx('9', '9999', 25, $precision) . "\n";echo "9^99999,& & & & precision 15, iters 25 = " . bcpowx('9', '99999', 25, $precision) . "\n";echo "9^999999,& & && precision 15, iters 25 = " . bcpowx('9', '999999', 25, $precision) . "\n";echo "9^9999999,& & & precision 15, iters 25 = " . bcpowx('9', '9999999', 25, $precision) . "\n";echo "9^,& && precision 15, iters 25 = " . bcpowx('9', '', 25, $precision) . "\n";echo "9^,& & precision 15, iters 25 = " . bcpowx('9', '', 25, $precision) . "\n";echo "9^,&& precision 15, iters 25 = " . bcpowx('9', '', 25, $precision) . "\n";echo "9^,& precision 15, iters 25 = " . bcpowx('9', '', 25, $precision) . "\n";echo "9^, precision 15, iters 25 = " . bcpowx('9', '', 25, $precision) . "\n"; ?&
Inspired by dawidgarus' implementation, here's my simple bc math helper, it does not support function calls, but supports boolean comparisons and is about ~40% faster.&?phpfunction bc() {& & $argv = func_get_args();& & $string = str_replace(' ', '', "({$argv[0]})");& & $operations = array();& & if (strpos($string, '^') !== false) $operations[] = '\^';& & if (strpbrk($string, '*/%') !== false) $operations[] = '[\*\/\%]';& & if (strpbrk($string, '+-') !== false) $operations[] = '[\+\-]';& & if (strpbrk($string, '&&!=') !== false) $operations[] = '&|&|=|&=|==|&=|!=|&&';& & $string = preg_replace('/\$([0-9\.]+)/e', '$argv[$1]', $string);& & while (preg_match('/\(([^\)\(]*)\)/', $string, $match)) {& & & & foreach ($operations as $operation) {& & & & & & if (preg_match("/([+-]{0,1}[0-9\.]+)($operation)([+-]{0,1}[0-9\.]+)/", $match[1], $m)) {& & & & & & & & switch($m[2]) {& & & & & & & & & & case '+':& $result = bcadd($m[1], $m[3]);& & & & & & & & & & case '-':& $result = bcsub($m[1], $m[3]);& & & & & & & & & & case '*':& $result = bcmul($m[1], $m[3]);& & & & & & & & & & case '/':& $result = bcdiv($m[1], $m[3]);& & & & & & & & & & case '%':& $result = bcmod($m[1], $m[3]);& & & & & & & & & & case '^':& $result = bcpow($m[1], $m[3]);& & & & & & & & & & case '==':& & & & & & & & & & case '=':& $result = bccomp($m[1], $m[3]) == 0;& & & & & & & & & & case '&':& $result = bccomp($m[1], $m[3]) == 1;& & & & & & & & & & case '&':& $result = bccomp($m[1], $m[3]) ==-1;& & & & & & & & & & case '&=': $result = bccomp($m[1], $m[3]) &= 0;& & & & & & & & & & case '&=': $result = bccomp($m[1], $m[3]) &= 0;& & & & & & & & & & case '&&':& & & & & & & & & & case '!=': $result = bccomp($m[1], $m[3]) != 0;& & & & & & & & }& & & & & & & & $match[1] = str_replace($m[0], $result, $match[1]);& & & & & & }& & & & }& & & & $string = str_replace($match[0], $match[1], $string);& & }& & return $string;}?&
A little comment for the simplified example above: you can do base converting without BCMath functions using only math operators, but you will not able to manage very large values or work with strings to compress or scramble data. If you have BCMath installed in your system it worth use it for this.
A found a little fix to do in my base2dec() function:The line "if($base&37) $value=strtolower($value);" should be removed if you want to specify another digits for your base conversions. Change it this way:if(!$digits) {$digits=digits($base);if($base&37) {$value=strtolower($value);}}Another example using these functions is to generate a key for a session, to name temporary files or something else:srand((double) microtime()*1000000);$id=uniqid(rand(10,999));$mykey=dec2base(base2dec($id,16),64);$mykey is a base64 value, which is a good key for passing thru an URL and also is shorter than a MD5 string (it will be allways 11 chars long). If you need something more secure, just scramble the 64 digits in the digits() function.Well, I hope you enjoy it.Regards,Edemilson Lima
Function to round bc string:
&?php
function bcround($strval, $precision = 0) {
& & if (false !== ($pos = strpos($strval, '.')) && (strlen($strval) - $pos - 1) & $precision) {
& & & & $zeros = str_repeat("0", $precision);
& & & & return bcadd($strval, "0.{$zeros}5", $precision);
& & } else {
& & & & return $strval;
& & }
}
?&
Like any other bc function, you can't trust the last couple of digits, but everything else seems to check out.& If you want to use this for anything important, you may want to verify this against other sources of pi before use.& This function calculates 100 decimal places of pi in 329 iterations -- not exactly fast (each iteration calls the factorial function, from below, twice), so I try to avoid calling it more than once.&?//arbitrary precision pi approximator//author tom boothby//free for any usefunction bcpi() {& & $r=2;& & $i=0;& & $or=0;& & while(bccomp($or,$r)) {& & & & $i++;& & & & $or=$r;& & & & $r = bcadd($r,bcdiv(bcmul(bcpow(bcfact($i),2),& & & & & & & & & & & & bcpow(2,$i+1)),bcfact(2*$i+1)));& & }& & return $r;}?&
Here's a function to compute the natural exponential function in arbitrary precision using the basic bcMath arithmetic operations.EXAMPLE:To compute the exponential function of 1.7 to 36 decimals:$y = bcExp("1.7", 36);The result:4.would be returned in variable $yNOTE:In practice, the last couple of digits may be inaccurate due to small rounding errors.& If you require a specific degree of precision, always compute 3-4 decimals beyond the required precision.The program code for the natural exponential function is:******************************************& Function bcExp($xArg, $NumDecimals){&& $x = Trim($xArg);&& $PrevSum& = $x - 1;&& $CurrTerm = 1;&& $CurrSum& = bcAdd("1", $x, $NumDecimals);&& $n& & & & = 1;&& While (bcComp($CurrSum, $PrevSum, $NumDecimals))& {&& $PrevSum& = $CurrS&& $CurrTerm = bcDiv(bcMul($CurrTerm, $x, $NumDecimals), $n + 1, $NumDecimals);&& $CurrSum& = bcAdd($CurrSum, $CurrTerm, $NumDecimals);&& $n++;& }&& Return $CurrS}
I spent some time looking for how to generate a large random number, in the end I've settled for reading directly from /dev/urandomI know this is a *nix only solution, but I figured that it might come in handy to someone else.The value $size is the size in bits, it could be simplified greatly if you want the size in bytes, but bits was more helpful to what I needed.&?phpfunction bcrand($size){& & $filename = "/dev/urandom";& & $handle = fopen($filename, "r");& & $bin_urand = fread($handle, ceil($size/8.0));& & fclose($handle);& & $mask = (($size % 8 & 5) ? '0' : '') . dechex(bindec(str_repeat('1', $size % 8))) . str_repeat('FF', floor($size/8));& & $binmask = pack("H*", $mask);& & $binrand = $binmask & $bin_urand;& & $hexnumber = unpack("H*", $binrand);& & $hexnumber = $hexnumber[''];& & $numlength = strlen($hexnumber);& & $decnumber = 0;& & for($x = 1; $x &= $numlength; $x++)& & {& & & & $place = $numlength - $x;& & & & $operand = hexdec(substr($hexnumber,$place,1));& & & & $exponent = bcpow(16,$x-1);& & & & $decValue = bcmul($operand, $exponent);& & & & $decnumber = bcadd($decValue, $decnumber);& & }& & return $decnumber;}?&
A simplier Version of the Script above:function dec2base($dec, $digits) { $value = ""; $base& = strlen($digits); while($dec&$base-1) {& $rest = $dec % $& $dec& = $dec / $& $value = $digits[$rest].$ } $value = $digits[intval($dec)].$ return (string) $}function base2dec($value, $digits) { $value = strtoupper($value); $base& = strlen($digits); $size& = strlen($value); $dec&& = '0'; for ($loop = 0; $loop&$ $loop++) {& $element = strpos($digits,$value[$loop]);& $power&& = pow($base,$size-$loop-1);& $dec& & += $element * $ } return (string) $}$digits = "ABCDEFGHJKLMNPQRSTUVWXYZ";echo dec2base('1000', $digits);
Oops, first posting contained wrong code... sorry.An amendment to the entry by pulstar at mail dot com - the digits() function can be made much faster (remove the line breaks from the big string, and make sure you don't miss any characters!):function digits2($base) {& & if($base & 64) {& & & & return substr('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_', 0, $base);& & } else {& & & & return substr("\x0\x1\x2\x3\x4\x5\x6\x7\x8\x9\xa\xb\xc\xd\xe\xf\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f\x20!\x22#\x24%&'()*+,-./:;&=&\x3f@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff", 0, $base);& & }}in my benchmarks, this is around 150x faster for 256 digits
If you too are confused with illegible code like this:&?php$a = "3";$b = "5";bcadd(bcmod(bcadd(bcdiv(bcsqrt(bcadd(7, bcpow($a, 2))), 4), $b), "4"), "0.5"); ?&You may consider use my function, which makes example above look:&?phpbc("(sqrt(7 + $1^2) / 4 + $2) % 4 + 0.5", "3", "5");?&Code:&?phpfunction bc() {& & & & $functions = 'sqrt';& & & & $argv = func_get_args();& & & & $string = str_replace(' ', '', '('.$argv[0].')');& & & & $string = preg_replace('/\$([0-9\.]+)/e', '$argv[$1]', $string);& & & & while (preg_match('/(('.$functions.')?)\(([^\)\(]*)\)/', $string, $match)) {& & & & & & & & while (& & & & & & & & & & & & preg_match('/([0-9\.]+)(\^)([0-9\.]+)/', $match[3], $m) ||& & & & & & & & & & & & preg_match('/([0-9\.]+)([\*\/\%])([0-9\.]+)/', $match[3], $m) ||& & & & & & & & & & & & preg_match('/([0-9\.]+)([\+\-])([0-9\.]+)/', $match[3], $m)& & & & & & & & ) {& & & & & & & & & & & & switch($m[2]) {& & & & & & & & & & & & & & & & case '+': $result = bcadd($m[1], $m[3]);& & & & & & & & & & & & & & & & case '-': $result = bcsub($m[1], $m[3]);& & & & & & & & & & & & & & & & case '*': $result = bcmul($m[1], $m[3]);& & & & & & & & & & & & & & & & case '/': $result = bcdiv($m[1], $m[3]);& & & & & & & & & & & & & & & & case '%': $result = bcmod($m[1], $m[3]);& & & & & & & & & & & & & & & & case '^': $result = bcpow($m[1], $m[3]);& & & & & & & & & & & & }& & & & & & & & & & & & $match[3] = str_replace($m[0], $result, $match[3]);& & & & & & & & }& & & & & & & & if (!empty($match[1]) && function_exists($func = 'bc'.$match[1]))& {& & & & & & & & & & & & $match[3] = $func($match[3]);& & & & & & & & }& & & & & & & & $string = str_replace($match[0], $match[3], $string);& & & & }& & & & return $string;}?&Note you must define scale with bcscale().
As "benjcarson at digitaljunkies dot ca" () noted in the first two comments, bcmath doesn't accept exponential notation.Moreover, you might have other problems if you feed the bcmath functions directly with floating point numbers.Consider the following example:&?phpbcscale(1);$a = 0.8;$b = 0.7;var_dump((string) $a);&& var_dump((string) $b);&& var_dump(bcadd($a, $b)); setLocale(LC_ALL, 'fr_BE.UTF-8');var_dump((string) $a);&& var_dump((string) $b);&& var_dump(bcadd($a, $b)); ?&The floating point numbers passed to the bcadd() function are automatically converted to string using the localized decimal separator. However, the bcmath functions always use a full stop, which results in the last result being incorrect.Below is a function to convert floating point numbers to strings correctly. It takes care of the decimal separator and the exponential notation. It also preserve the precision without drifting away (e.g. 1.0 doesn't become 0.99999...)&?phpfunction bcconv($fNumber){& & $sAppend = '';& & $iDecimals = ini_get('precision') - floor(log10(abs($fNumber)));& & if (0 & $iDecimals)& & {& & & & $fNumber *= pow(10, $iDecimals);& & & & $sAppend = str_repeat('0', -$iDecimals);& & & & $iDecimals = 0;& & }& & return number_format($fNumber, $iDecimals, '.', '').$sAppend;}?&Example:&?phpsetLocale(LC_ALL, 'fr_BE.UTF-8'); $precision = ini_get('precision') + 2; bcscale($precision);$big = pow(10, $precision);$small = 1 / $big;var_dump(bcconv($big + $small));& & & & & & && var_dump(bcadd($big, $small));& & & & & & & && var_dump(bcadd(bcconv($big), bcconv($small))); ?&The first result's precision loss is due to PHP's internal floating point numbers' representation.The second result is wrong because of the localized decimal separator.Finally, the last result is correct.
Code below implements standard rounding on 5 or higer round up, else don't round.& There wasn't a round function for the BC functions, so here is a simple one that works. Same args as round, except takes strings and returns a string for more BC operations.----------------function roundbc($x, $p) {& && $x = trim($x);& && $data = explode(".",$x);& && if(substr($data[1],$p,1) &= "5") {& & & & && //generate the add string.& & & & && $i=0;& & & & && $addString = "5";& & & & && while($i & $p) {& & & & & & && $addString = "0" . $addS& & & & & & && $i++;& & & & && }//end while.& & & & && $addString = "." . $addS& & & & && //now add the addString to the original fraction.& & & & && $sum = bcadd($data[0] . "." . $data&& [1],$addString,$p+1);& & & & && //explode the result.& & & & && $sumData = explode(".",$sum);& & & & && //now, return the correct precision on the rounded number.& & & & && return $sumData[0] . "." . substr($sumData[1],0,$p);& & & } else {& & & & && //don't round the value and return the orignal to the desired& & & & && //precision or less.& & & & && return $data[0] . "." . substr($data[1],0,$p);& & & }//end if/else.&& }//end roundbc.
I hacked these taylor expansions up to make diagrams for some physics homework.& I don't think you'll be wanting to do any real science with PHP... but what the hell, why not?& I plan to implement either a spigot algorithm or something similar to generate pi in the near future.&?// arbitrary precision sin and cosine functions// author tom boothby// free for any usefunction bcfact($n) {& & $r = $n--;& & while($n&1) $r=bcmul($r,$n--);& & return $r;}function bcsin($a) {& & $or= $a;& & $r = bcsub($a,bcdiv(bcpow($a,3),6));& & $i = 2;& & while(bccomp($or,$r)) {& & & & $or=$r;& & & & switch($i%2) {& & & & & case 0:& $r = bcadd($r,bcdiv(bcpow($a,$i*2+1),bcfact($i*2+1)));& & & & & default: $r = bcsub($r,bcdiv(bcpow($a,$i*2+1),bcfact($i*2+1)));& & & & }& & & & $i++;& & }& & return $r;}function bccos($a) {& & $or= $a;& & $r = bcsub(1,bcdiv(bcpow($a,2),2));& & $i = 2;& & while(bccomp($or,$r)) {& & & & $or=$r;& & & & switch($i%2) {& & & & & case 0:& $r = bcadd($r,bcdiv(bcpow($a,$i*2),bcfact($i*2)));& & & & & default: $r = bcsub($r,bcdiv(bcpow($a,$i*2),bcfact($i*2)));& & & & }& & & & $i++;& & }& & return $r;}?&

我要回帖

更多关于 指数函数 的文章

 

随机推荐