Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

printf doubles with %lf gives nan #58

Closed
ahgamut opened this issue Feb 26, 2021 · 2 comments · Fixed by #66
Closed

printf doubles with %lf gives nan #58

ahgamut opened this issue Feb 26, 2021 · 2 comments · Fixed by #66
Assignees

Comments

@ahgamut
Copy link
Collaborator

ahgamut commented Feb 26, 2021

Hi, I tried out a bunch of portable executables in Linux and Windows, and they all worked perfectly :).

However, when I compiled and ran the below code:

int main() {
    double x = 0.25;
    double y = sin(x);
    printf("sin(%f) = %f\n", x, y);
    printf("sin(%lf) = %lf\n", x, y);
    return 0;
}

The output is:

sin(0.250000) = 0.247404
sin(0.000000) = nan

When I compile using gcc -lm the output is same for both.
Do I have to add a compilation flag to print doubles via %lf?

@ahgamut ahgamut mentioned this issue Feb 26, 2021
@alisonatwork
Copy link
Contributor

I believe this might be a bug. I haven't had time to compile the project yet, but this might fix it.

--- a/libc/fmt/palandprintf.c
+++ b/libc/fmt/palandprintf.c
@@ -215,6 +215,10 @@ hidden int palandprintf(void *fn, void *arg, const char *format, va_list va) {
         signbit = sizeof(intmax_t) * 8 - 1;
         break;
       case 'l':
+        if (format[1] == 'f' || format[1] == 'F') {
+          format++;
+          break;
+        }
         if (format[1] == 'l') format++;
         /* fallthrough */
       case 't': /* ptrdiff_t */

See: https://en.cppreference.com/w/c/io/fprintf

%lf and %lF (plus a couple other float formats) should resolve to double, not long double.

@jart
Copy link
Owner

jart commented Feb 27, 2021

Thank you not only for bringing this to my attention, but for taking the time to send a PR too.

One thing worth mentioning is that the best way to format floats is Cosmopolitan is by doing the following:

printf("%s\n", gc(xdtoa(3.14)));

That's the wrapper we define for generalized dtoa which in my opinion formats much more readable numbers than the standard for the printf interface would otherwise enable us to do.

I should also mention that Cosmopolitan's floating point printf() is somewhat underdeveloped for that reason. The main thing it's lacking right now is exponents. It also isn't femtoscale accurate like the generalized dtoa functions are.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants