PHP rechnet falsch!



  • Hat sich geklärt! SORRY!

    Hi.
    Ich möchte ein Programm zur Binomialverteilung schreiben und habe gemerkt, dass PHP falsch rechnet.
    Habe nämlich die Formel und Funktionen 1:1 in C++ portiert und dort kommen die richtigen Werte raus.
    So hier zuerst mal den PHP-Code: (für n wird 2 übergeben und für p wird 0.5 übergeben)

    <?php
      header("Content-type: image/png");
    
      function fak($zahl){
        if($zahl<=1||!is_int($zahl))
          return 1;
    
        $erg=1;
        for(; $zahl>0; $zahl--){
          $erg*=$zahl;
        }
    
        return $erg;
      };
    
      $n=$_GET["n"];
      $p=$_GET["p"];
    
      $bild = imagecreate(800, 500);
      $hint = ImageColorAllocate($bild, 255, 255, 255);
    
      $text_farbe = ImageColorAllocate ($bild, 0, 0, 0);
    
      if($_GET["akt"]==1){
        $breite=800/($k+1)-80;
        $max=0;
        $hoehe=0;
        $werte=array();
        for($i=0; $i<=$n; $i++){
          $temp=((fak($n)/(fak($n-$i)*fak($i)))*pow($p,$i)*pow((1-$p),($n-$i)));
    
          if($temp>$max){
            $max=$temp;
          }
    
          $werte[]=$temp;
        }
    
        for($i=0; $i<=$n; $i++){
          ImageString($bild, 6, 0, $hoehe, "i=$i n=$n p=$p Wert=$werte[$i]", $text_farbe);
          $hoehe+=15;
        }
      }
    
      imagepng($bild);
    ?>
    

    Dieser Code rechnet folgende Werte:
    0.125
    0.25
    0.125

    Hier der Code in C++, bei dem ich die Formel 1:1 kopiert habe:

    #include <cstdlib>
    #include <iostream>
    #include <math.h>
    
    using namespace std;
    
    long double fak(int zahl)
    {
    	if(zahl<=1)
    		return 1;
    	long double erg=1;
    	for(; zahl>0; zahl--)
    	{
    		erg*=zahl;
    	}
    	return erg;	
    };
    
    int main(int argc, char *argv[])
    {
    	int n=2;
    	float p=0.5;
    
    	for(int i=0; i<=n; i++)
    	{
    		cout<<"i="<<i<<" n="<<n<<" p="<<p<<" Wert="<<((fak(n)/(fak(n-i)*fak(i)))*pow(p,i)*pow((1-p),(n-i)))<<endl;
    	}
        system("PAUSE");
        return EXIT_SUCCESS;
    }
    

    Hier kommen 0.25, 0.5 und 0.25 raus, was auch richtig ist.
    Jemand ne Ahnung, warum das so ist?



  • schoen dass es sich geklaert hat 🙂 Koenntest du bitte trotzdem sagen woran's lag? 🙂


Anmelden zum Antworten