Вычисления над числами с произвольной точностью BCMath
This extension is an interface to the GNU implementation as a library of the Basic Calculator utility by Philip Nelson; hence the name.
8 years ago
Note that when you use implementation of factorial that ClaudiuS made, you get results even if you try to calculate factorial of number that you normally can’t, e.g. 2.5, -2, etc. Here is safer implementation:
/**
* Calculates a factorial of given number.
* @param string|int $num
* @throws InvalidArgumentException
* @return string
*/
function bcfact ( $num )
if (! filter_var ( $num , FILTER_VALIDATE_INT ) || $num <= 0 ) throw new InvalidArgumentException ( sprintf ( 'Argument must be natural number, "%s" given.' , $num ));
>
for ( $result = ‘1’ ; $num > 0 ; $num —) $result = bcmul ( $result , $num );
>
10 years ago
Needed to compute some permutations and found the BC extension great but poor on functions, so untill this gets implemented here’s the factorial function:
/* BC FACTORIAL
* n! = n * (n-1) * (n-2) .. 1 [eg. 5! = 5 * 4 * 3 * 2 * 1 = 120]
*/
function bcfact ( $n ) $factorial = $n ;
while (— $n > 1 ) $factorial = bcmul ( $factorial , $n );
return $factorial ;
>
print bcfact ( 50 );
//30414093201713378043612608166064768844377641568960512000000000000
?>
6 years ago
Useful function for bcround
function getBcRound($number, $precision = 0)
$precision = ($precision < 0)
? 0
: (int) $precision;
if (strcmp(bcadd($number, ‘0’, $precision), bcadd($number, ‘0’, $precision+1)) == 0) return bcadd($number, ‘0’, $precision);
>
if (getBcPresion($number) — $precision > 1) $number = getBcRound($number, $precision + 1);
>
$t = ‘0.’ . str_repeat(‘0’, $precision) . ‘5’;
return $number < 0
? bcsub($number, $t, $precision)
: bcadd($number, $t, $precision);
>
function getBcPresion($number) $dotPosition = strpos($number, ‘.’);
if ($dotPosition === false) return 0;
>
return strlen($number) — strpos($number, ‘.’) — 1;
>
var_dump(getBcRound(‘3’, 0) == number_format(‘3’, 0));
var_dump(getBcRound(‘3.4’, 0) == number_format(‘3.4’, 0));
var_dump(getBcRound(‘3.56’, 0) == number_format(‘3.6’, 0));
var_dump(getBcRound(‘1.95583’, 2) == number_format(‘1.95583’, 2));
var_dump(getBcRound(‘5.045’, 2) == number_format(‘5.045’, 2));
var_dump(getBcRound(‘5.055’, 2) == number_format(‘5.055’, 2));
var_dump(getBcRound(‘9.999’, 2) == number_format(‘9.999’, 2));
var_dump(getBcRound(‘5.0445’, 5) == number_format(‘5.044500’, 5));
var_dump(getBcRound(‘5.0445’, 4) == number_format(‘5.04450’, 4));
var_dump(getBcRound(‘5.0445’, 3) == number_format(‘5.0445’, 3));
var_dump(getBcRound(‘5.0445’, 2) == number_format(‘5.045’, 2));
var_dump(getBcRound(‘5.0445’, 1) == number_format(‘5.05’, 1));
var_dump(getBcRound(‘5.0445’, 0) == number_format(‘5.0’, 0));//
var_dump(getBcRound(‘5.04455’, 2) == number_format(‘5.045’, 2));
var_dump(getBcRound(‘99.999’, 2) == number_format(‘100.000’, 2));
var_dump(getBcRound(‘99.999’) == number_format(‘99.999’, 0));
var_dump(getBcRound(‘99.999’, ‘a’) == number_format(‘99.999’, 0));
var_dump(getBcRound(‘99.999’, -1.5) == number_format(‘99.999’, 0));
var_dump(getBcRound(‘-0.00001’, 2) == number_format(‘-0.000’, 2));
var_dump(getBcRound(‘-0.0000’, 2) == number_format(‘0’, 2));
var_dump(getBcRound(‘-4.44455’, 2) == number_format(‘-4.445’, 2));
var_dump(getBcRound(‘-4.44555’, 0) == number_format(‘-4.5’, 0));
var_dump(getBcRound(‘-4.444444444444444444444444444444444444444444445’, 0) == number_format(‘-4.5’, 0));
9 years ago
It’s worth noting that this library is named very wrongly.
It may be called ‘Binary Calculator’, but what you’re getting is a decimal calculator that can represent base-10 fractions accurately.
6 years ago
Useful function for bcround
function getBcRound($number, $precision = 0)
$precision = ($precision < 0)
? 0
: (int) $precision;
if (strcmp(bcadd($number, ‘0’, $precision), bcadd($number, ‘0’, $precision+1)) == 0) return bcadd($number, ‘0’, $precision);
>
if (getBcPresion($number) — $precision > 1) $number = getBcRound($number, $precision + 1);
>
$t = ‘0.’ . str_repeat(‘0’, $precision) . ‘5’;
return $number < 0
? bcsub($number, $t, $precision)
: bcadd($number, $t, $precision);
>
function getBcPresion($number) $dotPosition = strpos($number, ‘.’);
if ($dotPosition === false) return 0;
>
return strlen($number) — strpos($number, ‘.’) — 1;
>
var_dump(getBcRound(‘3’, 0) == number_format(‘3’, 0));
var_dump(getBcRound(‘3.4’, 0) == number_format(‘3.4’, 0));
var_dump(getBcRound(‘3.56’, 0) == number_format(‘3.6’, 0));
var_dump(getBcRound(‘1.95583’, 2) == number_format(‘1.95583’, 2));
var_dump(getBcRound(‘5.045’, 2) == number_format(‘5.045’, 2));
var_dump(getBcRound(‘5.055’, 2) == number_format(‘5.055’, 2));
var_dump(getBcRound(‘9.999’, 2) == number_format(‘9.999’, 2));
var_dump(getBcRound(‘5.0445’, 5) == number_format(‘5.044500’, 5));
var_dump(getBcRound(‘5.0445’, 4) == number_format(‘5.04450’, 4));
var_dump(getBcRound(‘5.0445’, 3) == number_format(‘5.0445’, 3));
var_dump(getBcRound(‘5.0445’, 2) == number_format(‘5.045’, 2));
var_dump(getBcRound(‘5.0445’, 1) == number_format(‘5.05’, 1));
var_dump(getBcRound(‘5.0445’, 0) == number_format(‘5.0’, 0));//
var_dump(getBcRound(‘5.04455’, 2) == number_format(‘5.045’, 2));
var_dump(getBcRound(‘99.999’, 2) == number_format(‘100.000’, 2));
var_dump(getBcRound(‘99.999’) == number_format(‘99.999’, 0));
var_dump(getBcRound(‘99.999’, ‘a’) == number_format(‘99.999’, 0));
var_dump(getBcRound(‘99.999’, -1.5) == number_format(‘99.999’, 0));
var_dump(getBcRound(‘-0.00001’, 2) == number_format(‘-0.000’, 2));
var_dump(getBcRound(‘-0.0000’, 2) == number_format(‘0’, 2));
var_dump(getBcRound(‘-4.44455’, 2) == number_format(‘-4.445’, 2));
var_dump(getBcRound(‘-4.44555’, 0) == number_format(‘-4.5’, 0));
var_dump(getBcRound(‘-4.444444444444444444444444444444444444444444445’, 0) == number_format(‘-4.5’, 0));
- Copyright © 2001-2023 The PHP Group
- My PHP.net
- Contact
- Other PHP.net sites
- Privacy policy
Bcmath php как включить
Поведение этих функций зависит от установок в php.ini .
Имя | По умолчанию | Место изменения | Список изменений |
---|---|---|---|
bcmath.scale | «0» | PHP_INI_ALL |
Для подробного описания констант PHP_INI_*, обратитесь к разделу Где могут быть установлены параметры конфигурации.
Краткое разъяснение конфигурационных директив.
Число десятичных цифр для всех bcmath-функций. Смотрите также bcscale() .
User Contributed Notes
There are no user contributed notes for this page.
- Установка и настройка
- Требования
- Установка
- Настройка во время выполнения
- Типы ресурсов
- Copyright © 2001-2023 The PHP Group
- My PHP.net
- Contact
- Other PHP.net sites
- Privacy policy
Почему не устанавливается расширение php-bcmath?
Доброго времени суток, я тут пытаюсь поднять контейнер на докере, но почему то расширение php-bcmath не устанавливается.
Сам DockerFile
FROM ubuntu:18.04 # Устанавливаем время ENV TZ=Asia/Almaty RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone # Создаем рабочую папку RUN mkdir /var/www WORKDIR /var/www # Обновляем APT RUN apt-get update -y # Устанавливаем системные зависимости RUN apt-get install -y nano git mc net-tools cron curl software-properties-common # Устанавливаем PHP7 RUN ln -sf /var/log/php7.3-fpm.log /dev/stdout RUN add-apt-repository ppa:ondrej/php -y RUN apt-get update -y RUN apt-get install -y php7.3 php7.3-fpm php7.3-pgsql php7.3-curl php7.3-dom php7.3-gd php7.3-mbstring php7.3-zip php-soap php-dompdf php-bcmath php7.3-ldap RUN sed -i -e "s/pid =.*/pid = \/var\/run\/php7.3-fpm.pid/" /etc/php/7.3/fpm/php-fpm.conf RUN sed -i -e "s/error_log =.*/error_log = \/proc\/self\/fd\/2/" /etc/php/7.3/fpm/php-fpm.conf RUN sed -i -e "s/;daemonize\s*=\s*yes/daemonize = no/g" /etc/php/7.3/fpm/php-fpm.conf RUN sed -i "s/listen = .*/listen = 9000/" /etc/php/7.3/fpm/pool.d/www.conf RUN sed -i "s/;catch_workers_output = .*/catch_workers_output = yes/" /etc/php/7.3/fpm/pool.d/www.conf # Устанавливаем composer RUN php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" && php composer-setup.php --install-dir=/usr/bin --filename=composer && chmod +x /usr/bin/composer && php -r "unlink('composer-setup.php');" # Устанавливаем npm RUN apt-get install -y npm ENTRYPOINT php-fpm7.3 CMD ["-F", "-R"] EXPOSE 9000
В списке расширений его нет
Хотя если попытаться установить через терминал, он говорит что уже установлен
- Вопрос задан более трёх лет назад
- 1041 просмотр
2 комментария
Средний 2 комментария
Enable BCMath using php.ini?
I need to enable BC Math, but I don’t want to do it using —enable-bcmath, primarily because I don’t understand that route. Is there a way to do this using php.ini only?
asked Apr 25, 2013 at 14:44
user1262516 user1262516To the best of my knowledge you must compile php with the —enable-bcmath option. Without it, the required code won’t exist in the binary. Therefore, there is nothing that you can set in php.ini.
Apr 25, 2013 at 15:00
I can’t accept your answer, as it’s only a comment. If you want to put it as an answer I’ll accept it.
– user1262516
Apr 28, 2013 at 14:462 Answers 2
To the best of my knowledge you must compile php with the —enable-bcmath option. Without it, the required code won’t exist in the binary. Therefore, there is nothing that you can set in php.ini
answered May 2, 2013 at 14:38
2,372 6 6 gold badges 36 36 silver badges 58 58 bronze badges
or apt-get install php5-bcmath
May 2, 2013 at 14:40
I’m getting Unable to locate package php5-bcmath . Does it have a different name now?
Feb 5, 2014 at 18:51@nkamm In Ubuntu (and it’s save to assume in Debian as well), bcmath is included as part of the php5 source package and all php5 binary packages in Ubuntu and Debian (since php 5.3.10 at least) have bcmath included by default, so you do not need to install any additional packages to get it. I can show evidence (for Ubuntu at least) that supports this statement.
Feb 5, 2014 at 19:17
Just go for «php-bcmath», it’ll install the most recent package (today it’d be php7-bcmath)
Jan 28, 2017 at 12:21@manniL is right that php-bcmath installs latest — but be aware — you only want that if you also want to have latest php — if your project runs e.g. on php 5.4 , install php5 packages 😉 Sidenote: on Ubuntu 18.04 I had to install this package manually (for php 7.2.1)