D
D
Decker2016-02-23 23:52:00
PHP
Decker, 2016-02-23 23:52:00

PHP. Multiplication of 6 floats, the commutative law of multiplication does not work?

An interesting logic puzzle. Everyone knows about the commutative law of multiplication, i.e. that A*B*C = A*C*B ... a simple PHP example for real numbers showing that this is not the case:

<?php

$d4 = 6031 * 8109 * 980 * 1909 * 429 * 1714;
var_dump($d4);
var_dump(sprintf("%020.0f",$d4));

$d4 = 8109 * 980 * 1909 * 429 * 1714 * 6031;
var_dump($d4);
var_dump(sprintf("%020.0f",$d4));

?>

We get the result:
float(6.7275470345782E+19)
string(20) "67275470345782386688"
float(6.7275470345782E+19)
string(20) "67275470345782378496"

Those. in the first case we have 67275470345782386688, and in the second case with the same factors 67275470345782378496.
Two questions.
1. Why? (I understand that the error accumulates at each stage of multiplication due to float precision)
2. In what order does PHP parse the first expression? Those. in what order are the actions performed in the expression 6031 * 8109 * 980 * 1909 * 429 * 1714 ? How it is possible to repeat the given result "on steps"?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey, 2016-02-24
@Decker

https://en.wikipedia.org/wiki/IEEE_754-1985
In PHP, the multiplication operator is left associative, i.e. the expression is evaluated from left to right. In your case - in order.

$d4 = ((((6031 * 8109) * 980) * 1909) * 429) * 1714;

E
Eugene, 2016-02-24
@Nc_Soft

NEVER perform arithmetic operations in PHP without special libraries

php >  echo bcmul(6031, bcmul(8109, bcmul(980, bcmul(1909, bcmul(429, 1714, 0), 0), 0), 0), 0);
67275470345782378680
php > echo bcmul(8109, bcmul(980, bcmul(1909, bcmul(429, bcmul(1714, 6031, 0), 0), 0), 0), 0);
67275470345782378680

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question