Seltsames verhalten bei simpler Rechnung



  • Hallo, ich habe ein Problem mit folgendem Code:

    #include<stdio.h>                                                               #include <math.h>
    
    int main(void)
    {
        double T = 7005;
        double rho = 3.59178e-20 * 0.7;
        double a = (2.11/rho) * exp(-52490.0/T);
    
        printf("%g\n", sqrt(a*a + 4.0*a));
        //printf("%g\n", a*a + 4.0*a);
    
        double solution = (-a/2.0) + sqrt(a*a + 4.0*a) / 2.0;
        printf("solution = %g\n", solution);
    
        return(0);
    }
    

    Kommentiere ich das zweite printf aus bekomme ich am Ende "solution = 0", kommentiere ich das erste printf aus bekomme ich am Ende "solution = 1".
    Auf 64Bit Rechnern scheint immer "solution = 0" zu kommen, egal was auskommentiert ist.
    Ist das ein ueberlauf im double? Warum beeinflusst das Auskommentieren von einem printf das ergebniss, dort wird ja keine Variable geaendert?
    Schonmal viele Dank fuer jede Hilfe, ich stehe im Moment auf dem Schlauch...

    M.



  • Die Loesung ist allgemein auch nicht richtig ...



  • markusBR schrieb:

    Ist das ein ueberlauf im double?

    (-a/2.0) und sqrt(a*a + 4.0*a) sind mit der präzision von double einfach gleich groß. Mit long double kriege ich 2.21875 als Lösung raus, ist das richtig?

    #include<stdio.h>                                                              
    #include<math.h> 
    
    int main(void) 
    { 
        long double T = 7005; 
        long double rho = 3.59178e-20 * 0.7; 
        long double a = (2.11/rho) * exp(-52490.0/T); 
    
        long double solution = (-a/2.0) + sqrt(a*a + 4.0*a) / 2.0; 
        printf("solution = %Lg\n", solution); 
    
        return(0); 
    }
    

    Dafür brauchst du natürlich einen compiler der long double kann (gcc z.b.).



  • So ist das eben, wenn man sehr grosse mit sehr kleinen Zahlen multipliziert.



  • Jup, so gehts, Danke 🙂


Anmelden zum Antworten