Open In App

PHP Program to Calculate Root Mean Square

Root Mean Square (RMS) is a statistical measure of the magnitude of a varying quantity. It is commonly used in physics, engineering, and statistics to represent the effective value of a set of numbers. In this article, we will discuss how to calculate the RMS of a set of numbers in PHP using different approaches.



Calculate Root Mean Square using a Loop

This approach in the provided PHP program iterates through each number in the given array, squares each number, and then calculates the mean of the squares. Finally, it computes the square root of the mean of the squares to obtain the Root Mean Square (RMS) value.



Example: Implementation to calculate root mean square.




<?php
  
function calculateRMS($numbers) {
    $sumOfSquares = 0;
    $count = count($numbers);
  
    foreach ($numbers as $number) {
        $sumOfSquares += pow($number, 2);
    }
  
    $meanOfSquares = $sumOfSquares / $count;
    $rms = sqrt($meanOfSquares);
  
    return $rms;
}
  
// Driver code
$numbers = [2, 3, 4, 5];
$rms = calculateRMS($numbers);
echo "Root Mean Square: " . $rms;
  
?>

Output
Root Mean Square: 3.6742346141748

Explanation:

Calculate Root Mean Square using Array Functions

PHP provides built-in array functions that can be used to calculate RMS in a more concise way.

Example: Implementation to calculate root mean square.




<?php
  
function calculateRMS($numbers) {
    $square = function($n) { 
        return pow($n, 2); 
    };
      
    $squaredNumbers = array_map($square, $numbers);
      
    $meanOfSquares = array_sum($squaredNumbers) / count($numbers);
      
    $rms = sqrt($meanOfSquares);
  
    return $rms;
}
  
// Driver code
$numbers = [2, 3, 4, 5];
$rms = calculateRMS($numbers);
echo "Root Mean Square: " . $rms;
  
?>

Output
Root Mean Square: 3.6742346141748

Explanation:


Article Tags :