php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #51547 Type casting from int to int after log changes value
Submitted: 2010-04-13 11:03 UTC Modified: 2010-04-13 11:26 UTC
From: acollins at liv dot ac dot uk Assigned:
Status: Not a bug Package: *Math Functions
PHP Version: 5.2.13 OS:
Private report: No CVE-ID: None
View Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
If you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: acollins at liv dot ac dot uk
New email:
PHP Version: OS:

 

 [2010-04-13 11:03 UTC] acollins at liv dot ac dot uk
Description:
------------
When performing a log(), and immediately type casting afterwards, the value changes.

Test script:
---------------
<?php
$val = 1000;
echo log($val, 10) .' == '. (int) log($val, 10);
?>

Expected result:
----------------
3 == 3

Actual result:
--------------
3 == 2

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2010-04-13 11:04 UTC] acollins at liv dot ac dot uk
Note: I assume this is because log() returns a floating point value. I.e. it's a precision issue?
 [2010-04-13 11:24 UTC] degeberg@php.net
-Status: Open +Status: Bogus
 [2010-04-13 11:24 UTC] degeberg@php.net
Floating point values have a limited precision. Hence a value might 
not have the same string representation after any processing. That also
includes writing a floating point value in your script and directly 
printing it without any mathematical operations.

If you would like to know more about "floats" and what IEEE
754 is, read this:
http://docs.sun.com/source/806-3568/ncg_goldberg.html
 
Thank you for your interest in PHP.

Try having a look at this:
echo serialize(log(1000, 10));

When you cast to int you just truncate the fractional part.
 [2010-04-13 11:26 UTC] aharvey@php.net
Exactly right: the first value is being rendered as 3 because of the fact that PHP limits the significant digits shown when converting a float to a string. If you look at the value of serialize(log(1000, 10)), you'll end up with something like the following:

d:2.999999999999999555910790149937383830547332763671875;

Which demonstrates that the internal representation is slightly less than 3. The explicit conversion to an integer causes the value to be rounded down, hence why you get 2.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Dec 05 05:01:31 2024 UTC