# Announcing new posts on Mastodon

With lots of people, including me, either starting up new Mastodon accounts or dusting off the old ones they created during a previous Twitter crisis, I decided to write a script that would autotoot to Mastodon whenever I publish a new post here. It didn’t take long, as the Mastodon API is pretty easy to use. I put everything together while watching college football.1

If you want to write your own autotooting script, you’d do well to start by reading this post at DEV instead of following the Getting Started section of the API docs. The DEV post’s author, Joseph, makes the very useful suggestion to get your script’s authorization credentials through the Mastodon web interface instead of interacting with the API directly. Had I done that to begin with, it would have saved me about a quarter’s worth of time and frustration.

You get the authorization credentials by navigating to the Development page of your Mastodon account profile, clicking the NEW APPLICATION button, and filling in a couple of fields. Don’t bother changing the redirects or the scopes; the default entries will be fine.

With that done, you’ll have an access token to use in your script. The part of the script that creates a new status is really short, thanks to the wonders of Kenneth Reitz’s Requests module. Here are the key parts of my autotooting script:

python:
1:  #!/usr/bin/env python3
2:
3:  import requests
4:
5:  [ more imports ]
6:
7:  # Mastodon information.
8:  murl = 'https://mastodon.cloud/api/v1/statuses'
9:  auth = {'Authorization': 'Bearer XXXXXXXXXXXXXXXXXXXX'}
10:
11:  [ Stuff to collect the info I want in the toot. ]
12:  [ The pieces of text I need are the summary ]
13:  [ and URL of the post. They're stored in variables ]
14:  [ named "summary" and "url." ]
15:
16:  toot = {'status': f'''☃️ {summary}\n{url}'''}
17:
18:  # Send the toot and return its URL.
19:  r = requests.post(murl, data=toot, headers=auth)
20:  print(r.json()['uri'])


The Mastodon URL you post to (Line 8) will depend on which server you’re hosted at. The bunch of Xs in Line 9 is replaced by the access token described above. The text of your toot goes into the status field of a dictionary (Line 16) that’s passed as the data parameter to the Requests post command (Line 19). That’s all.

Well, there is one other thing you may want to know. As you’re writing and debugging your script, you probably don’t want your followers to keep seeing your test toots. But you do want to see them yourself so you can make sure they’re working. To do that, add a visibility field to the toot dictionary.

16:  toot = {'status': f'''☃️ {summary}\n{url}''', 'visibility': 'direct'}


By setting the visibility to direct, it will act like a direct message to no one. Only you will see it. After debugging, just remove that part. Thanks to mdhughes for the tip.

1. I will not mention the game, because the results were disgusting. I guess schools that are academically inferior need to win football games to make their alumni feel better about themselves.

# Are you a mod or a rocker?

This post was supposed to go up just a few days after the last one, but stuff got in the way. At least we’re in the same month.

Shortly after that post went up, I got an email from reader Jason Reene.

When I plug “tan^-1(cot(x))” into my TI-89 (still my go-to quick symbolic algebra tool) it returns “mod(-x, π) - π/2”

It took me a few minutes to convince myself that was an equivalent result.

It took me a lot longer to convince myself that it was equivalent, partly because I wasn’t sure how the TI-89 handles the mod function when the dividend is negative and the divisor is positive, but mostly because I was having a hard time figuring out which quadrant mod(-x, n) would be in for a given quadrant of x.

But it does work, even for angles well outside the (0, π/2) domain that my problem was restricted to. Here’s Mathematica’s plot of ArcTan[Cot[x]] over (-π, π):

And here’s its plot of Mod[-x, Pi] - Pi/2 over the same domain:

Apparently, Mathematica treats the Mod function the same way Jason’s TI-89 does. Not all programming languages do.

After making these plots, I started thinking about the tangent, inverse tangent, and modulo functions, and how their definitions could easily change the answers Jason and I got.

Let’s start with tangent and its inverse. Here’s the tangent plotted over a decent range of angles:

To see its inverse, we exchange the horizontal and vertical axes:

Because this has multiple values for every argument, we have to choose which one our inverse tangent function will return. This is called the principal value. As far as I know, every programming language and every calculator chooses the one I’ve made a darker blue—the one that returns a value between -π/2 and π/2. So if you ask your calculator for the inverse tangent of a positive number, it gives you an angle in the first quadrant; if you ask it to give you the inverse tangent of a negative number, it gives you an angle in the fourth quadrant.

And if you’ve forgotten what that “quadrant” stuff is, this should refresh your memory. The arrows point in the positive directions.

Let’s move on to modulo. This is basically what you learned as “remainder” when you were first doing division. And when you’re dealing with positive integers only, modulo is exactly what you learned back then. Extending modulo to non-integer numbers is straightforward, but the tricky bits come when either the dividend (the number you’re dividing) or the divisor (the number you’re dividing it by) are negative.

For example, if you want -7 mod 3, you could think of it as

7 = 3 × (-2) – 1


so -7 mod 3 would be –1. Or you could think of it as

7 = 3 × (-3) + 2


and -7 mod 3 would be 2. Both answers are valid, but if you’re designing a programming language or a calculator, you have to choose one or the other. For this problem, Perl, Python, and Ruby return 2, while AppleScript and JavaScript return -1.

There’s a lot more to modulo—we haven’t discussed the divisor being negative—but that’s enough for our purposes. You can look up the various definitions on Wikipedia.

When the dividend is negative and the divisor positive, both Mathematica and the TI-89 return a positive result, which is why my Mod graph above (made in Mathematica) and the result from Jason’s calculator agree.

To show how tricky the TI-89’s formula is, let’s see how it transforms an angle in the first quadrant. We’ll use π/6, the same angle we converted with the ArcTan[Cot[θ]] formula in the last post. You can see the manipulations graphically in this image:

The hardest part to visualize is, of course, the modulo operation. It’s the smallest counterclockwise angle from an integer multiple of π to the purple line that was drawn in Step 2. In this case, the multiple of π we use is –π, the negative x-axis, and the CCW angle to the purple line is 5π/6.

As you can see, we do get to π/3, just not as easily as we did in the last post, where we just took the complement of the angle. On the other hand, this modulo formula works for angles outside of the first quadrant, and Jason’s TI-89 came up with it on its own. As you recall, Mathematica got stuck on ArcTan[Cot[θ]] and wouldn’t reduce it further. We had to figure out that it was the complement of π ourselves.

Thanks to Jason for an interesting view on this problem, and congratulations to the computer algebra people at Texas Instruments for a clever solution.

# Simplifying trig expressions

When using any computer algebra system, there comes a time when you wonder why the result produced by the program isn’t as simple as you could make it by hand. To get good at using such a system, you have to learn its tricks of substitution and simplification.

Quite often, the results seem more complicated than they should because you carry in your head certain underlying assumptions about the nature of the variables that you haven’t told the program about.

For example, I’ve seen Mathematica return this,

$\sqrt{r^2}$

which seems weird until you realize that it doesn’t know that $r$ is a postive—or at least nonnegative—number. But if I add this at the top of the notebook,

$Assumptions = r ≥ 0  Mathematica does what I expect and simplifies the root to just $r$. Once I learned about $Assumptions, and the related Assuming function and Assumptions option, I got more of the results I was expecting from Mathematica. But I’m still struggling with trigonmetric simplifications. Over the weekend, I was doing a definite integral, and got a result that included this term:

ArcTan[Cot[θ]]


First, I was a little surprised to see cotangent, a function I haven’t used since high school (or maybe even junior high). For whatever reason, the mathematical derivations I’ve seen since college have eschewed the upside-down trig functions—secant, cosecant, and cotangent—in favor of dividing by their “regular” counterparts. The only exception I can think of is the secant formula for eccentrically loaded columns.

Anyway, there certainly has to be a simpler way of expressing the arctangent of the cotangent of an angle. I tried everyone’s first line of defense, Simplify, and just got ArcTan[Cot[θ]] back. I then tried TrigExpand, TrigReduce, and TrigFactor without much hope of success, as they’re geared toward rewriting powers of trig functions and trig functions applied to multiple angles. I got what I expected: still just ArcTan[Cot[θ]].

It didn’t take too much thought to get the simplified answer I was looking for: the complement of $\theta$. Consider this plot of tangent (blue) and cotangent (red) in the first quadrant.1

They are mirror images of each other about $\pi/4$. So if we start at some angle, say $\pi/6$, on the horizontal axis and go up to the red line, we’ll get its cotangent. Running horizontally over to the blue line gives us the arctangent of that value, which we read by dropping back down to the horizontal axis. Because of the mirror symmetry, we end up at the complement of our starting angle. Or, in algebraic terms,

$\tan^{-1}(\cot \theta) = \frac{\pi}{2} - \theta$

Of course, I didn’t get this result through Mathematica, I got it through thinking.

I was able to use Mathematica to confirm this result, but it was by a roundabout path. I plotted ArcTan[Cot[θ]] over the first quadrant and got what looked like a nice straight line.

If it is a straight line, the slope should be –1 everywhere. To check this, I took the derivative:

Come on, Mathematica, you can do better than that. I applied TrigFactor to the result and (finally) got –1. The y-intercept looks like it’s at π/2, which I confirmed through

I couldn’t just plug in 0 for θ, because the cotangent of 0 is undefined. And I had to use a directional limit, because the limit from below goes to –π/2.

Although I got Mathematica to confirm that ArcTan[Cot[θ]] is π/2 – θ, I never got it to give me that answer itself. Maybe that’s because Mathematica thinks ArcTan[Cot[θ]] is a superior answer; more likely, it’s because I haven’t been using it long enough to know its tricks.

1. The physical problem I was dealing with meant the angle was always going to be in the first quadrant—between 0 and π/2 radians or 0° and 90°. And in case you’re wondering, yes, I did include that restriction in my \$Assumptions declaration; but it didn’t help.

# Orbital curvature

Last week, John Cook wrote a nice post on the shape of the Moon’s orbit. He was inspired by a paper written by Noah Samuel Brannen for the College Mathematics Journal back in 2001.1 The gist of their analyses is that if you trace out the Moon’s path as it and the Earth travel around the Sun, you will find—probably to your surprise—that the shape you get is convex everywhere. Even when the Moon is new, and it’s between the Earth and the Sun, its path is still bending toward the Sun and not toward the Earth.

As it happens, I was not surprised to see this. I first read about it in one of Isaac Asimov’s science books back when I was a teenager. It’s stuck with me all these years, mainly because I didn’t really understand it and couldn’t visualize it. But after reading Cook and Brannen and fiddling around in Mathematica, I finally get it, some 45 years later.

Because the orbits of both the Moon and the Earth have low eccentricities, we can model them both as circles. Using Brannen’s coordinate system, with the origin at the Sun, the x and y position of the Moon can be expressed in parametric form as

$x(\theta) = d \cos \theta + \cos p\, \theta$ $y(\theta) = d \sin \theta + \sin p\, \theta$

where we have taken the radius of the Moon’s orbit to be 1, and

• $\theta$ is the angular position of the Earth in its orbit around the Sun;
• $p$ is the number of times the Moon orbits the Earth during a year; and
• $d$ is the radius of the Earth’s orbit.

With this coordinate system, $x$ and $y$ are measured not in miles or kilometers, but in multiples of the Moon’s orbital radius. That may seem weird, but it’s often convenient to put things in nondimensional form like this.

Mathematica knows the orbital radii of the Earth and Moon so we can get the value of $d$ via

 d = Entity["Planet", "Earth"]["AverageOrbitDistance"] /
Entity["PlanetaryMoon", "Moon"]["AverageOrbitDistance"]


which is 388.6. Similarly, we can get the orbital periods of the Earth and Moon using

TEarth = Entity["Planet", "Earth"]["OrbitPeriod"]


which gives 365.25636 days, and

TMoon = Entity["PlanetaryMoon", "Moon"]["OrbitPeriod"]


which gives 27.322 days. Thus,

p = TEarth / TMoon


is 13.369.

You may be questioning these numbers. After all, doesn’t the Gregorian calendar tell us a year is about 365.2425 days long?2 And isn’t the time between new moons more like 29½ days? Yes, but these common values are from an Earth-centric frame of reference. The values we need for our equations are the sidereal (relative to the stars) values. Luckily, Mathematica gives us the sidereal figures, rather than the tropical year (365.2422 days) or the synodic month (29.53 days).

So if we plug these values in for $d$ and $p$ and plot out a year’s worth of Moon positions, we get this shape:

This is roughly a circle, but you can see the waviness. It’s an SVG image, so you can zoom in as far as you like. Or you can look at this section of the path, where I’ve added a blue dashed line to represent the Earth’s orbit.

This certainly looks like a convex figure, but how can we be sure? Brannen does so by investigating the curvature of the path. If the curvature is positive throughout the path, the curve is convex.

(If you’re wondering—as I was—why that’s so, go back to the definition of curvature. Curvature is the rate of change of direction of a line tangent to the path with movement along the path. In our situation, the Moon is moving counterclockwise along the red path in the figure above. If the tangent to the path is rotating counterclockwise as the Moon moves, then the path is convex—it’s always bulging outward.)

Mathematica has a function, ArcCurvature, that I thought would do what I wanted without fiddling with all the individual derivatives. But while ArcCurvature does return the curvature for a curve expressed in parametric form, it gives the unsigned curvature. So instead of taking a Mathematica shortcut, we have to go the long way around.

For a path defined parametrically, the curvature is

$\kappa = \frac{x^{\prime} y^{\prime\prime} - y^{\prime} x^{\prime\prime}}{\:\:\left({x^{\prime}}^2 + {y^{\prime}}^2 \right)^{3/2}}$

where the primes indicate differentiation with respect to $\theta$.

Because the denominator is the power of a sum of squares, it’s always positive. So the sign of $\kappa$ depends on the sign of the numerator. For our parametric equations, the numerator works out to be

$d^2 + p^3 + d\,p\,(p+1)\, \cos (1 - p) \theta$

Since cosine can’t be less than –1, the smallest this expression can be is

$d^2 + p^3 - d\,p\,(p+1)$

which factors to

$(d - p) (d - p^2)$

Looking back at our values for $d$ and $p$ above, it’s clear that both of these terms are positive, so our curvature is positive for all values of $\theta$. Hence, the Moon’s path around the Sun is convex.

Let’s move on to Isaac Asimov. What he did that’s stuck with me all these years is compare the gravitational pull of the Sun on the Moon to the gravitational pull of the Earth on the Moon. He started with Newton’s Law of Gravitation,

$F = \frac{G \, m_1 \, m_2}{r^2}$

and compared the force associated with the Moon/Sun system to that of the Moon/Earth system. The ratio, after the common terms drop out, is

$\frac{m_S/m_E}{\left( r_S/r_E \right)^2}$

where

• $m_S$ and $m_E$ are the masses of the Sun and Earth; and
• $r_S$ and $r_E$ are the distances of the Moon to the Sun and Earth.

You’d be hard-pressed to find a reference with a table that gives you the mean distance from the Moon to the Sun, but it is, of course, the same as the orbital radius of the Earth. So the ratio in the denominator is just the value of $d$ we were using in our earlier calculations.

The mass ratio can be calculated from Mathematica’s built-in data:

mRatio = Entity["Star", "Sun"]["Mass"] /
Entity["Planet", "Earth"]["Mass"]


which works out to $3.329 \times 10^5$. The force ratio, then, is

$\frac{3.329 \times 10^5}{388.6^2} = 2.2$

In other words, the Sun exerts more than twice as much gravitational force on the Moon as the Earth does. Asimov argued that this means the Moon is really orbiting the Sun, with some perturbation by the Earth, and that’s why the Moon’s path looks like a slightly wobbly circle around the Sun.

But Asimov didn’t get into the kind of detail about the Moon’s orbit the way Cook and Brannen did, so I had a hard time getting this image of its path—which comes from Brannen’s paper—out of my head.

Now I know better.

I was going to leave it there, but curiosity got the better of me. I wanted to find the Asimov book with this material and see if my memory was right.3 I knew that the book was one of his collections of science essays, probably a collection of his monthly columns in The Magazine of Fantasy and Science Fiction. Because these collections were often themed and given titles like Asimov on Something, I searched for Asimov on Astronomy.

I got a hit right away. The Internet Archive has a scan of the book, and Chapter 9, “Just Mooning Around,” has the stuff I remembered, although he calculated the force ratio the other way around, with the force of the Earth on the Moon being 0.46 that of the Sun. Here’s his conclusion:

We might look upon the Moon, then, as neither a true satellite of the Earth, nor captured one, but as a planet, in its own right, moving about the Sun, in careful step with the Earth. To be sure, from within the Earth-Moon system, the simplest way of picturing the situation is to have the Moon revolve about the Earth; but if you were to draw a picture of the orbits of the Earth and Moon about the Sun, exactly to scale, you would see that the Moon’s orbit is everywhere concave toward the Sun. It is always “falling” toward the Sun.

Asimov on Astronomy came out in 1974. The “Just Mooning Around” column was first published in the May 1963 issue of F&SF and had been previously collected in Of Time and Space and Other Things. Since I was being a completist, I grabbed the magazine cover image from the Internet Speculative Fiction Database.

This is what the internet is for.

1. The DOI of Brannen’s paper is 10.1080/07468342.2001.11921888, so those of you with accounts at academic libraries can use that to get a copy. The rest of us can use Sci-Hub (whose home page may have moved by the time you read this).

2. That’s 365 days in a normal year, plus one for every leap year (0.25), minus one for three out of every four century years (0.0075).

3. Since I’ve added this section, it’s a good bet that it was.