Calculating a cotangent equation in Scala

One of my nieces had a homework problem where she had to graph the x and y values of this cotangent equation:

y = 3 * cotangent(4 * x)

I couldn’t remember how to graph things like that just by looking at the equation, so I wrote this Scala “cotangent” program:

package cotangent

object CotangentProblem extends App {
    // create a simpler name for PI, then use it
    val PI = Math.PI
    val xValues = List(0, PI/16, PI/8, 3*PI/16, PI/4)

    // a cotangent function
    def cotan(x: Double) = 1 / Math.tan(x)

    // the equation we're supposed to solve and graph
    def yOfX(x: Double) = 3 * cotan(4 * x)

    // a method to print the results
    def printResult(x: Double, y: Double) { println(f"y($x%-6.4f) = $y%-6.4f") }

    // loop through the x values and print the results
    for (x <- xValues) {
        val y = yOfX(x)
        printResult(x, y)


Cotangent output

Here’s what the output of the program looks like:

y(0.0000) = Infinity
y(0.1963) = 3.0000
y(0.3927) = 0.0000
y(0.5890) = -3.0000
y(0.7854) = -24496859029793056.0000

My niece tells me that the values where x equals 0 and PI/4 are the asymptotes of this problem.


A few comments on the Scala code:

  • A cotangent is just the inverse of the tangent.
  • The Math.tan function expects the value it’s given to be expressed in radians (not degrees).
  • The xValues were given to her by her teacher.
  • I could have printed the output differently, but I used Scala’s “f interpolator” to control the way the output was printed.

If for any reason you wanted to see how to calculate the cotangent of numbers in Scala, I hope this code is helpful.