math

Functional programming: Math functions, not programming functions

“There’s only ONE rule, but it’s an important one: all of your values must be functions. Not programming functions, but math functions.”

I think I read that quote in an earlier version of this article. The quote is about functional programming, and it influenced something I wrote in my book, Functional Programming, Simplified: Functional programmers think about themselves as being mathematicians, and think of their code as being a combination of algebraic equations, where each function is a pure function that you can think of in mathematical terms.

Scala Vector informational and mathematical methods (syntax, examples)

This page contains a collection of examples of how to use Scala Vector class informational and mathematical methods. Note that these same methods will also work with a Scala Seq, including IndexedSeq.

Informational and mathematical methods

As the name implies, these methods let you get information about the contents of a Vector, or perform mathematical expressions on a Vector.

A Java method to round a float value to the nearest one-half value

As a quick note, here’s a Java method that will round a float to the nearest half value, such as 1.0, 1.5, 2.0, 2.5, etc.:

/**
 * converts as follows:
 * 1.1  -> 1.0
 * 1.3  -> 1.5
 * 2.1  -> 2.0
 * 2.25 -> 2.5
 */
public static float roundToHalf(float f) {
    return Math.round(f * 2) / 2.0f;
}

The comments show how this function converts the example float values to their nearest half value, so I won’t add any more details here. I don’t remember the origin of this algorithm — I just found it in some old code, thought it was clever, and thought I’d share it here.

Teaching the mathematics of infinity (and childrens’ brains)

Here’s an article with two interesting exercises near the end of it: How thinking about infinity changes kids’ brains on math. When you’re ready to go deeper, that article links to a NY Times article, Teaching the mathematics of infinity. And then that article links to another titled, The life of Pi and other infinities.

(When I was a young lad, I’d often lay in bed at night and wonder, “Okay, so I go to the edge of the universe ... what’s after that? There’s gotta be something after that, right?”)

The Scala power (exponentiation) function

I was just working on a math problem in Scala where I needed to get the exponent of a value, and after some research, I found that the right approach is to use the scala.math.pow function when you need the power/exponent of a value. Here's the output from a REPL command:

scala> scala.math.pow(2,3)
res1: Double = 8.0

I was originally using the Math.pow function, and getting a deprecation warning: