rhannequin / astronoby

Ruby library based on astronomy and astrometry books
https://dev.to/rhannequin/series/17782
MIT License
59 stars 2 forks source link

Refactor Angle as a single class #13

Closed rhannequin closed 9 months ago

rhannequin commented 9 months ago

Previously, there was three subclasses of Angle:

This was not a good approach for the universal notion of what an angle is. The same angle should not be represented by two different objects depending on their unit.

Now, only Angle remains. An angle is always stored with a radian unit, as it is the unit of angle in the International System of Units.

Converting an angle is not about changing its type anymore, but only converting its value from one unit to another. The value is nos accessible through the unit name:

angle = Astronoby::Angle.as_degrees(180)

angle.degrees # => 0.18e3
angle.radians # => 0.31415926...e1

Because angles in degrees and hours are immediately converted, some precision is immediately lost. However, the conversion is done with BigDecimal numbers with a precision of 14. I believe this is more than enough affordable precision loss for this project.

The reader may notice some test values have changed. Because I took the opportunity to remove the ceil method on the angle initialization, precision has actually increased. This change is barely noticeable because it affects far digits of the arc second. In the future, I will conduct performance tests to figure out if ceiling angles increase the library overall performance and speed of calculations.

Angles can still be initialized from different units with the following class methods:

String formatting has also changed and can be done immediately on the angle without the need to convert it to another unit before:

angle = Astronoby::Angle.as_degrees(180)
angle.str(:dms)

I will work on making Angle a better value object in the future, to make its use even more convenient and efficient.

Thanks to @JoelQ for inspiring me into this work.