Sunday 10 December 2023

The curse of the c++ switch/case

Yep, 5 hrs of modifications, trial & error without a catch and staying awake until some 5 or 6 AM.

My early/dirty stage of writing some numerical stuff allows me to select an algorithm to use. In fact I found out that I will have to use one of these inside the other to workaround some huge errors that seem inevitable in the n-body problem.

But instead of some fancy "factory"-like thing, I decided to leave the selection at an enum level, and forgot about the break statement in the switch/case. After hours of what-the-heck-ing I finally did what I should have done in the first place:

  • dive into some (more or less obscure to me) launch.json thing inside the .vscode directory, set the executable and arguments to run;
  • add -g and remove -02 from the compiler flags, optimization seems to make gdb or other stuff like breakpoint setting behave so weirdly;
  • and boom - see right away (in the call stack) that the damn thing was using the "wrong" algorithm. 

That's because of the "fallthrough" feature of the C++'s switch/case thing. Moral of the story that I didn't know about, but now it seems elementary: switch/case is not just a replacement of if/else-if/else. And sticking to the common meaning of the term "case" is a waste of time and shooting myself in the foot.

You're not drunk; you're just stupid ...

I should have figured it out really quick. It's two masses orbiting around their center of mass. And it seemed that only one of these motions is seriously messed up, being piece-wise uniform, making the other go around some "slowly rotating ellipse". 

But earlier it was me who had been whining about the algorithm generating some serious errors. Essentially: making both total energy and angular momentum change in a step-wise manner while. And both orbits of the 2-body system grow somewhat fat during the bodies' fly-by, where their velocities and accelerations are large enough. And I started writing some "refined" version that would estimate the bodies' accelerations and treat the "dangerous" sub-systems separately (first approximation: use a time-step smaller by an order of magnitude, perhaps some better algorithm than "leapfrog"). But all I left there was some lousy "partitioning" of the n-body system into "safe" and "flyby" subsets. And the "todo" (empty) loop for the fly-bys - with no warning, "not implemented" exception throwing or so.

No comments:

Post a Comment