PHP - Serialize floating points

前端 未结 9 1507
自闭症患者
自闭症患者 2021-01-02 02:19

I am generating 10 random floats between 6 and 8 (all for good reason), and writing them to a mysql database in a serialized form. But one quirk seems to emerge at the stora

9条回答
  •  没有蜡笔的小新
    2021-01-02 03:02

    Here's my take on Gumbo's answer. I put IteratorAggregate on there so it would be foreach-able, but you could add Countable and ArrayAccess also.

    factor = $factor;
        $this->store = $data;
      }
    
      public function __sleep()
      {
        array_walk( $this->store, array( $this, 'toSerialized' ) );
        return array( 'factor', 'store' );
      }
    
      public function __wakeup()
      {
        array_walk( $this->store, array( $this, 'fromSerialized' ) );
      }
    
      protected function toSerialized( &$num )
      {
        $num *= $this->factor;
      }
    
      protected function fromSerialized( &$num )
      {
        $num /= $this->factor;
      }
    
      public function getIterator()
      {
        return new ArrayIterator( $this->store );
      }
    }
    
    function random_float ($min,$max) {
       return ($min+lcg_value()*(abs($max-$min)));
    }
    
    $original = array();
    for ( $i = 0; $i < 10; $i++ )
    {
      $original[] = round( random_float( 6, 8 ), 1 );
    }
    
    $stored = new FloatStorage( $original );
    
    $serialized = serialize( $stored );
    $unserialized = unserialize( $serialized );
    
    echo '
    ';
    print_r( $original );
    print_r( $serialized );
    print_r( $unserialized );
    echo '
    ';

提交回复
热议问题