Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Split up long C++ double literal into multiple lines

I’m implementing log_10(x) in terms of log_2(x) with the following formula
log_10(x) = log_2(x)/log_2(10).
I want to make this function generic (eg I would like it to work with could work with Boost’s cpp_bin_float_quad) and, as far as I know, there’s no great way to compute log_2(10) at compile time, so I just pasted in a long literal for 1/log_2(10). The following code works but I have some issues with it:

template <typename T>
static inline T log(T x){
    T invlog2of10 = 0.301029995663981195213738894724493l;
    return invlog2of10*log2(x);
}

Issue 1: The literal is so many characters long that it makes vim slow and it breaks the syntax highlighting. Is there a standard compliant way to split this floating-point literal into multiple lines? Doing so would fix the syntax highlighting and then it’d be clearer how many digits there are in the literal.
Issue 2: Is long double really the highest precision I can use for this literal? Computing this constant at compile time would be much more ideal.

I tried putting spaces, newlines, and and backslashes into the floating-point literal similar to what can be done for long string literals. This did not work.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Use a backslash:

T invlog2of10 = 0.301029995663981\
195213738894724493l;

The backslash escapes the newline.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading