top | item 40925329

(no title)

dctwin | 1 year ago

I was able to do the primitive

long double result = 0.0;

while (...) {

  if (json[head] == '.') ...

  result *= 10; result += json[head] - '0';
}

in a constexpr function with no problem :)

discuss

order

svalorzen|1 year ago

The problem with this is that it will not actually parse double in IEEE 754, as you will accumulate inaccuracies at every step of the loop. In theory, when parsing a float, you are supposed to return the floating point that is closest to the original string number. Your code will not do that. Even if you accept the inaccuracy, if you for some reason load the JSON using a runtime library, you'll get different numbers and consequently and result that depend on those numbers. For my use-case this was not acceptable unfortunately..

dctwin|1 year ago

Yes, very true. I noticed that even already at 3dp the floats start to compare unequal. The long double helped but it's not really.

I googled and found two examples of constexpr float parsing repositories, but from the sounds of things, you understand this problem better than I and will have seen them already

kookybakker|1 year ago

How about floats in scientific notation?

dctwin|1 year ago

You can do something similar, no? std::pow is not constexpr (most float stuff is not, presumably due to floating point state) but you can implement 10^x anyway