A Java method to calculate the NFL Passer Rating

Note: The code below is based on the Wikipedia formula, which is not correct. The correct algorithm seems to be at this page. I’ll update the code below once I verify this for sure.

In working on my “XO Play” Android football game, I just created this Java method to calculate the NFL Passer Rating for my quarterbacks:

private double calculateNflPasserRating(int attempts, int completions, int passingYards, int tds, int ints) {
    if (attempts == 0) return 0;
    double a = ((double)completions  / (double)attempts - 0.3) * 5.0;
    double b = ((double)passingYards / (double)attempts - 3.0) * 0.25;
    double c = ((double)tds          / (double)attempts) * 20.0;
    double d = 2.375 - ((double)ints / (double)attempts * 25.0);
    double passerRating = ( (a+b+c+d) / 6.0 ) * 100.0;
    return (passerRating < 0) ? 0.0 : passerRating;
}

If you haven’t seen it before, that last line uses the Java ternary operator syntax. I usually don’t care for that syntax too much, but it’s okay here.

I got the generic NFL Passer Rating algorithm from this Wikipedia page.

You don’t need all of the `(double)` casts

You don’t need quite as many (double) casts as I show in the code ... this is a better/simpler version of that method:

private double calculateNflPasserRating(int attempts, int completions, int passingYards, int tds, int ints) {
    if (attempts == 0) return 0;
    double a = ((double)completions  / attempts - 0.3) * 5.0;
    double b = ((double)passingYards / attempts - 3.0) * 0.25;
    double c = ((double)tds          / attempts) * 20.0;
    double d = 2.375 - ((double)ints / attempts * 25.0);
    double passerRating = ( (a+b+c+d) / 6.0 ) * 100.0;
    return (passerRating < 0) ? 0.0 : passerRating;
}

According to the Java mixed division rules, all you need is one double within a mixed arithmetic operation to yield a double.

I forgot that rule when writing the passer rating method, and just remembered it as I was typing this up.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.