User:Hossein/Blog/atan2

EasyHack: Use atan2 function instead of atan
When working with shapes and charts in LibreOffice, there are several occasions that you have to calculate. But is  function always the best choice? Here we discuss using  function instead of   in C++ code. When used in correct place,  can have a lot of benefits when calculating.



Unit circle
If you use  to calculate the output θ, you have to think about different situations that may occur, because with the same value of , there are multiple values of θ, and it would be your responsibility to handle that, and find out what is the suitable value of θ.

But, if you have two values  and , and you want to calculate  , there is a better choice: using. As discussed here,  can handle the values from all the 4 different quadrants.

This is the formula for :



atan2 formula
In this way, you don't have to check the sign of  and   because   does this by itself.

There are some places in the LibreOffice core that is currently using atan, and  is more suitable. For example, in hwpfilter/source/hcode.cxx:

A better choice would be this one single line:

Instead of multiplying the output of  by   to get degrees out of radians, we simply use   for the conversion, and also using the , those conditions would be superfluous, and are removed.

Finding instances of  to replace with

This  command shows the instances of the similar situations:

Within the results of the grep, you can find places that atan2 is better. You should take care about the conditions that may be present (or missing) after the atan. These conditions usually check the sign of the numerator and denominator in the fraction passed to atan. Make sure that the code works correctly after removing them.

Final Notes
Besides fixing the bugs, there are many places to work on improving the code, and some of these are listed as EasyHacks. The specific improvement that is discussed in this blog post is filed as tdf#145630.

If you want to work on this improvement, but you need to know how to get started with LibreOffice development, I suggest you to see our video tutorial:


 * YouTube: Getting Started with LibreOffice Development