diff options
-rw-r--r-- | ext/standard/basic_functions.c | 1 | ||||
-rw-r--r-- | ext/standard/math.c | 34 | ||||
-rw-r--r-- | ext/standard/php_math.h | 1 | ||||
-rw-r--r-- | ext/standard/tests/math/math_std_dev.phpt | 10 |
4 files changed, 46 insertions, 0 deletions
diff --git a/ext/standard/basic_functions.c b/ext/standard/basic_functions.c index fe9f781e84..3c11762634 100644 --- a/ext/standard/basic_functions.c +++ b/ext/standard/basic_functions.c @@ -415,6 +415,7 @@ function_entry basic_functions[] = { PHP_FE(base_convert, NULL) PHP_FE(number_format, NULL) PHP_FE(fmod, NULL) + PHP_FE(math_std_dev, NULL) #ifdef HAVE_INET_NTOP PHP_NAMED_FE(inet_ntop, php_inet_ntop, NULL) #endif diff --git a/ext/standard/math.c b/ext/standard/math.c index 289c3c491b..a1237165fd 100644 --- a/ext/standard/math.c +++ b/ext/standard/math.c @@ -1182,6 +1182,40 @@ PHP_FUNCTION(fmod) } /* }}} */ + + +/* {{{ proto float math_std_dev(array a) + Returns the standard deviation */ +PHP_FUNCTION(math_std_dev) +{ + double mean, sum = 0.0, vr = 0.0; + zval *arr, **entry; + HashPosition pos; + + if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "a", &arr) == FAILURE) { + return; + } + zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(arr), &pos); + while (zend_hash_get_current_data_ex(Z_ARRVAL_P(arr), (void **)&entry, &pos) == SUCCESS) { + convert_to_double_ex(entry); + sum += Z_DVAL_PP(entry); + zend_hash_move_forward_ex(Z_ARRVAL_P(arr), &pos); + } + mean = sum / zend_hash_num_elements(Z_ARRVAL_P(arr)); + + zend_hash_internal_pointer_reset_ex(Z_ARRVAL_P(arr), &pos); + while (zend_hash_get_current_data_ex(Z_ARRVAL_P(arr), (void **)&entry, &pos) == SUCCESS) { + double d; + convert_to_double_ex(entry); + d = Z_DVAL_PP(entry) - mean; + vr += d*d; + zend_hash_move_forward_ex(Z_ARRVAL_P(arr), &pos); + } + + RETURN_DOUBLE(sqrt(vr / zend_hash_num_elements(Z_ARRVAL_P(arr)))); +} +/* }}} */ + /* * Local variables: * tab-width: 4 diff --git a/ext/standard/php_math.h b/ext/standard/php_math.h index adbc9f8cdf..33efb0b9b2 100644 --- a/ext/standard/php_math.h +++ b/ext/standard/php_math.h @@ -59,6 +59,7 @@ PHP_FUNCTION(octdec); PHP_FUNCTION(base_convert); PHP_FUNCTION(number_format); PHP_FUNCTION(fmod); +PHP_FUNCTION(math_std_dev); PHP_FUNCTION(deg2rad); PHP_FUNCTION(rad2deg); diff --git a/ext/standard/tests/math/math_std_dev.phpt b/ext/standard/tests/math/math_std_dev.phpt new file mode 100644 index 0000000000..a68384c541 --- /dev/null +++ b/ext/standard/tests/math/math_std_dev.phpt @@ -0,0 +1,10 @@ +--TEST-- +math_std_dev() tests +--FILE-- +<?php +$a=array(4, 1, 7); +$dev=math_std_dev($a); +var_dump(sprintf("%2.9f", $dev)); +?> +--EXPECT-- +string(11) "2.449489743"
\ No newline at end of file |