# Math average with php

Time to test your math skills...

I'm using php to find the average of \$num1, \$num2, \$num3 and so on; upto an unset amount of numbers. It then saves that average to a database.

Next time the php script is called a new number is added to the mix.

Is there a math (most likely algebra) equation that I can use to find the average of the original numbers with the new number included. Or do I need to save the original numbers in the database so I can query them and re-calculate the entire bunch of numbers together?

If what you mean by average is mean and you don't want to store all numbers then store the amount of numbers:

```\$last_average = 100; \$total_numbers = 10; \$new_number = 54;```

``` ```

```\$new_average = ((\$last_average * \$total_numbers) + \$new_number) / (\$total_number + 1); ```

```array_sum(\$values) / count(\$values) ```

```Average = Sum / Number of values ```

Just store all 3 values, there's no need for anything complicated.

If you store the `Average` and `Sum` then calculate `Number of values` you'll lose a little accuracy due to truncation of Average.

If you store the `Average` and `Number of values` then calculate `Sum` you'll lose even more accuracy. You have more margin for error in calculating a correct value for `Number of values` than `Sum` thanks to it being an integer.

```<?php function avrg() { \$count = func_num_args(); \$args = func_get_args(); return (array_sum(\$args) / \$count); } ?> ```

http://php.net/manual/en/function.array-sum.php#101727

If you know the amount of numbers you can calculate the old sum, add the new one and divide by the old amount plus one.

```\$oldsum = \$average * \$amount; \$newaverage = (\$oldsum + \$newnum) / (\$amount + 1); ```

Thought that I should share my function

```function avg(\$sum=0,\$count=0){ return (\$count)? \$sum / \$count: NAN; } var_dump( avg(array_sum(\$values),count(\$values)) ); ```

Will return the average and also take into account 0, for example dividing by zero always returns NaN (Not a number)

1/0 = NaN
0/0 = NaN

Typically what you might do is save two pieces of information:

• the sum of all the numbers
• the count of numbers

Whenever you want to get the average, divide the sum by the count (taking care for the case of count == 0, of course). Whenever you want to include a new number, add the new number to the sum and increment the count by 1.

This is called a 'running average' or 'moving average'.

If the database stores the average and the number of values averaged, it will be possible to calculate a new running average for each new value.

```function avgvals(\$avg_vals,\$avg_delimiter=',') { if ( (is_string(\$avg_vals) && strlen(\$avg_vals) > 2) && (is_string(\$avg_delimiter) && !empty(\$avg_delimiter)) ) { \$average_vals = explode(\$avg_delimiter, \$avg_vals); \$return_vals = ( array_sum(\$average_vals) / count(\$average_vals) ); } elseif ( (is_string(\$avg_vals) && strlen(\$avg_vals) <= 2) && (is_string(\$avg_delimiter) && !empty(\$avg_delimiter)) ) { \$return_vals = \$avg_vals; } else { \$return_vals = FALSE; } return \$return_vals; } ```

You need to save all the original numbers in the database.

Category:php Views:1 Time:2010-01-10
Tags: php math average

## Related post

• How do I create an average from a Ruby array? 2009-08-27

How would get find an average from an array? If I have the array: [0,4,8,2,5,0,2,6] Averaging would give me 3.375. Thanks! --------------Solutions------------- Try this: arr = [5, 6, 7, 8] arr.inject{ |sum, el| sum + el }.to_f / arr.size => 6.5 No

• How do I use methods in classes decorated with DataContractAttribute in a WCF Client? 2010-07-22

I'm writing a .net WCF service. I've written a few classes that I want to return to the calling code from the WCF service; hence, I decorate them with the DataContract attribute. Let's suppose that my WCF service is called FooService. It contains a m

• .finding on a method in ActiveRecord 2010-09-09

I'm using ActiveRecord and Ruby (outside of Rails) to track some statistics. I added a method (total_cost) to one of my models to do calculations using a couple of the columns in the current model as well as a column from another model. I'd really li

• How to split a list? 2014-08-15

This question already has an answer here: Split string into a list in Python 12 answers I'm getting a list such as StudentStatus = ['Physics Pass', 'Chem Distinction', 'Maths Average'] I am printing it like: for each in StudentStatus: print each Henc

• How can I use Math::Business::EMA with DBI to calculate exponential moving averages in Perl? 2010-04-07

Script pulls data from mysql: \$DBI::result = \$db->prepare(qq{ SELECT close FROM \$table WHERE day <= '\$DATE' ORDER BY day DESC LIMIT \$EMA }); \$DBI::result->execute(); while(\$row = \$DBI::result->fetchrow) { print "\$row\n"; }; with the follo

• Should I use decimal, float or double for this simple math result? 2008-12-04

I'm doing some really simple math and saving the result to a MS SQL2008 DB. I'm averaging out the some numbers, which are byte values between 1<->5. I wish to record probably 2 decimal places only. I don't care about rounding for the 2nd decima

• Can I calculate the average of these numbers? 2008-12-04

I was wondering if it's possible to calculate the average of some numbers if I have this: int currentCount = 12; float currentScore = 6.1123 (this is a range of 1 <-> 10). Now, if I receive another score (let's say 4.5), can I recalculate the a

• Querying entity in NHibernate by average value of subentity 2009-01-17

I've got an entity Product like this: [Class(0, Name = "Product", Table = "Products")] public class Product { private readonly ISet<ProductPropertyValue> _productPropertyValues; private readonly ISet<ProductImage> _productImages; private

• How do you calculate the average of a set of angles? 2009-01-29

I want to calculate the average of a set of angles. For example, I might have several samples from the reading of a compass. The problem of course is how to deal with the wraparound. The same algorithm might be useful for a clockface. The actual ques

• How do I calculate the average direction of two vectors 2009-02-19

I am writing and opengl based iphone app and would like to allow a user to translate around a view based on the direction that they move two fingers on the screen. For one finger I know I could just calculate the vector from the start position to the

• Fixed point math in c#? 2009-03-03

I was wondering if anyone here knows of any good resources for fixed point math in c#? I've seen things like this (http://2ddev.72dpiarmy.com/viewtopic.php?id=156) and this (http://stackoverflow.com/questions/79677/whats-the-best-way-to-do-fixed-poin

• Clean way to reduce many TimeSpans into fewer, average TimeSpans? 2009-03-17

I have a C# Queue<TimeSpan> containing 500 elements. I need to reduce those into 50 elements by taking groups of 10 TimeSpans and selecting their average. Is there a clean way to do this? I'm thinking LINQ will help, but I can't figure out a cl

• Math.random() versus Random.nextInt(int) 2009-04-10

What is the difference between Math.random() * n and Random.nextInt(n) where n is an integer? --------------Solutions------------- Here is the detailed explanation of why "Random.nextInt(n) is both more efficient and less biased than Math.random() *

• How can I check for average concurrent events in a SQL table based on the date, time and duration of the events? 2009-04-17

I have a set of call detail records, and from those records, I'm supposed to determine the average concurrent active calls per system, per hour (at a precision of one minute). If I query 7pm to 8pm, I should see the average concurrent calls for the h

• How to Implement Generic Method to do Math calculations on different value types 2009-05-02

I have a method that accepts an IEnumerable-decimals and performance various math functions. I want to use the same method on an IEnumerable-int-. How do I implement this? For example to find a simple sum? void Calculate<T>(IEnumerable <T

• How would you describe math in comments? 2009-05-04

Well as the questions says... An equation might be more meaningful in its math-notated form than it is in code. Being able to put math in comments could improve readabibity on my projects. In .NET btw. --------------Solutions------------- I just use

• Get the most average position of X objects on a path with Y available positions 2009-05-08

Its friday, and in local time the clock is 3.22pm, so my brain wont give me a solution, so i ask: Im trying to write a function/algorithm in Actionscript 3.0 that gives me the most average positions of x number of positions along a path of y number o

• How do I find the average in a LARGE set of numbers? 2009-05-21

I have a large set of numbers, probably in the multiple gigabytes range. First issue is that I can't store all of these in memory. Second is that any attempt at addition of these will result in an overflow. I was thinking of using more of a rolling a

• Where are "Special Numbers" mentioned in Concrete Maths used? 2009-05-23

I was glancing through the contents of Concrete Maths online. I had at least heard most of the functions and tricks mentioned but there is a whole section on Special Numbers. These numbers include Stirling Numbers, Eulerian Numbers, Harmonic Numbers