This algebraic implementation follows AVG in pig built-in UDF: http://grepcode.com/file/repo1.maven.org/maven2/org.apache.pig/pig/0.11.1/org/apache/pig/builtin/AVG.java?av=f. It handles the invalid input as null.