Problem average Stock price

I have the problem that the average price per product changes if I

  • add 4 pcs @6.22050
  • remove this 4 pcs at this price
  • add 4 pcs again at 6.22050

the avg. price becomes 6.21437?

The routine is as follows:

        // we can not left join above because if no stock we would not receive the warehouse rowid!
        // so extra query to get stock in this warehouse

        $sqls =  "SELECT reel as stock FROM ". MAIN_DB_PREFIX. "product_stock  WHERE fk_entrepot = '".$rowe['rowid']."' AND fk_product = '".$object->id."';";

        $results = $db->query($sqls);
        if (! $results) {
                dol_print_error($db);
                exit;
        }
        if ( $results->num_rows == 1)
        {
            $rows=$results->fetch_array();
            print "      ".$lagerarr[$lrec]['arnr']." STOCK ALREADY in Dolibarr deleting ".$rows['stock']." #sql#".$sqls."\n";
            // subtract the full stock in dolibarr to be able to readd with correct average price
            $object->correct_stock(
                $fuser,
                $rowe['rowid'],
                $rows['stock'],
                '1',
                'Löschen Lagerbestand für Reimport des Bestandes mit korrektem Preis',
                $lagerarr[$lrec]['durchschnittlicherek'],
                '',
                '',
                null,
                '0',
                null
            );
        }

        // CAREFULLY! If stock in dolibarr already exists and is different then current, subtract full
        //            stock and readd full stock and price. otherwise the average price would change.
       // AVG CHANGES ???????

        $object->correct_stock(
            $fuser,
            $rowe['rowid'],
            $lagerarr[$lrec]['lagerstand'],
            '0',
            'import',
            $lagerarr[$lrec]['durchschnittlicherek'],
            '',
            '',
            null,
            '0',
            null
        );