|
|
 |
Los n煤meros de punto flotante (tambi茅n conocidos
como "flotantes", "dobles" o "n煤meros reales") pueden ser
especificados usando cualquiera de las siguientes sintaxis:
Formalmente:
El tama帽o de un flotante depende de la plataforma, aunque
un valor com煤n consiste en un m谩ximo de ~1.8e308 con
una precisi贸n de aproximadamente 14 d铆gitos
decimales (lo que es un valor de 64 bits en formato IEEE).
| Precisi贸n del punto flotante |
Es bastante com煤n que algunas fracciones decimales simples
como 0.1 o 0.7 no puedan
ser convertidas a su representaci贸n binaria interna sin
perder un poco de precisi贸n. Esto puede llevar a
resultados confusos: por ejemplo,
floor((0.1+0.7)*10) usualmente
devolver谩 7 en lugar del esperado
8 ya que el resultado de la
representaci贸n interna es en realidad algo como
7.9999999999....
Esto se encuentra relacionado al hecho de que es imposible
expresar de forma exacta algunas fracciones en notaci贸n
decimal con un n煤mero finito de d铆gitos. Por
ejemplo, 1/3 en forma decimal se convierte en
0.3333333. . ..
As铆 que nunca conf铆e en resultados de
n煤meros flotantes hasta el 煤ltimo d铆gito, y
nunca compare n煤meros de punto flotante para conocer si
son equivalentes. Si realmente necesita una mejor
precisi贸n, es buena idea que use las funciones matem谩ticas de precisi贸n
arbitraria o las funciones gmp en su lugar.
|
Para m谩s informaci贸n sobre cu谩ndo y
c贸mo son convertidas las cadenas a flotantes, vea la
secci贸n titulada Conversi贸n de
cadenas a n煤meros. Para valores de otros tipos, la
conversi贸n es la misma que si el valor hubiese sido
convertido a entero y luego a flotante. Vea la secci贸n
Conversi贸n
a entero para m谩s informaci贸n. A partir de
PHP 5, una noticia es generada si intenta convertir un objeto a
flotante.
add a note
User Contributed Notes
N煤meros de punto flotante
TAS
27-Jul-2006 04:02
An update regarding the james dot cridland at virginradio dot co dot uk note below, I recently tried his formula using PHP 5 and it is necessary to specify the integer precision when using the round function, otherwise the output will be 0.
<? echo round((69.1-floor(69.1))); ?> // prints 0
<? echo round((69.1-floor(69.1)), 1); ?> // prints 0.1
Also, it appears that "small numbers" include everything up to 64.0. So that
<? echo (63.1-floor(63.1)); ?>
will print 0.1 and
<? echo (64.0-floor(64.0)); ?>
will print 0, but
<? echo round(64.1-floor(64.1)); ?>
will print 0.099999999999994.
david at davidmosesNO dot SPAM dot ca
25-Mar-2006 01:48
Re: rick at ninjafoo dot com
There is no need to 鈥渁lways鈥 use the BCMath functions. We just need to heed the documentation and 鈥渘ever compare floating point numbers for equality鈥.
The reason (19.6*100) !== (double)1960, is because inside a computer they are not equal.
Try this:
<?php
printf("%.15f", (19.6*100));
?>
Outputs: 1960.000000000000227 (not 1960 as somewhat expected)
If comparison is required a few options come to mind (other than BCMath):
1) Round numbers before comparison:
<?php
$sig_figs = 5;
echo (round((19.6*100), $sig_figs) !== round((double)1960, $sig_figs)) ? 'not equal' : 'equal';
?>
Outputs: equal
2) Another method is to use a tolerance value, and consider numbers equal if their difference is less than the tolerance.
justin at jennnixon dot com
21-Nov-2005 04:00
I was playing around with a benchmark script:
<?php
$st = array_sum (explode (' ', microtime ()));
ob_start ();
for ($i = 1; $i < 10000; $i++) {
echo "<!-- Hello, World! " . ($i % round(sqrt($i*2))) ^ $i . " -->\n";
}
ob_end_flush ();
echo round ((array_sum (explode (' ',microtime ())) - $st), 5) . "\n";
?>
Be careful with numbers, they can print out inpredictable things. (For example, this printed out [uncommented])...
ᤊ 瘍੯ഘഀ潶ᄋ 瘍୯ഐഀ潶ጋ 瘍୯ഒഀ潶ᔋ 瘍୯ഔഀ潶ᜋ 瘍୯ഖഀ潶ᤋ 瘍୯ഘഀ潶ᄄ 瘍ѯഐഀ潶ጄ 瘍ѯഒഀ潶ᔄ 瘍ѯഔഀ潶ᜄ 瘍ѯഖഀ潶ᤄ 瘍ѯഘഀ潶ᄅ 瘍կഐഀ潶ጅ 瘍կഒഀ潶ᔅ 瘍կഔഀ潶ᜅ 瘍կഖഀ潶ᤅ ...
Luzian
17-Nov-2005 12:03
Be careful when using float values in strings that are used as code later, for example when generating JavaScript code or SQL statements. The float is actually formatted according to the browser's locale setting, which means that "0.23" will result in "0,23". Imagine something like this:
$x = 0.23;
$js = "var foo = doBar($x);";
print $js;
This would result in a different result for users with some locales. On most systems, this would print:
var foo = doBar(0.23);
but when for example a user from Germany arrives, it would be different:
var foo = doBar(0,23);
which is obviously a different call to the function. JavaScript won't state an error, additional arguments are discarded without notice, but the function doBar(a) would get 0 as parameter. Similar problems could arise anywhere else (SQL, any string used as code somewhere else). The problem persists, if you use the "." operator instead of evaluating the variable in the string.
So if you REALLY need to be sure to have the string correctly formatted, use number_format() to do it!
TRI0N
23-Sep-2005 07:01
Here is a simple formula to break down a number and get rid of the decimal values. I built this to take a number in seconds and convert it to a readable value for Server Uptimes.
<?php
$day = floor(($uptime / 86400)*1.0) ;
$calc1 = $day * 86400 ;
$calc2 = $uptime - $calc1 ;
$hour = floor(($calc2 / 3600)*1.0) ;
if ($hour < 10) {
$hour = "0".$hour ;
}
$calc3 = $hour * 3600 ;
$calc4 = $calc2 - $calc3 ;
$min = floor(($calc4 / 60)*1.0) ;
if ($min < 10) {
$min = "0".$min ;
}
$calc5 = $min * 60 ;
$sec = floor(($calc4 - $calc5)*1.0) ;
if ($min < 10) {
$sec = "0".$sec ;
}
$uptime2 = $day." Days, ".$hour.":".$min.":".$sec ;
?>
Place this where you want the results to be seen:
<?php echo $uptime2 ; ?>
For a Value of 1455587 seconds the results will show as followed:
16 Days, 20:19:47
Enjoy
rick at ninjafoo dot com
06-Jul-2005 01:04
Concider the following:
(19.6*100) != 1960
echo gettype(19.6*100) returns 'double', However even .....
(19.6*100) !== (double)1960
19.6*100 cannot be compaired to anything without manually
casting it as something else first.
(string)(19.6*100) == 1960
Rule of thumb, if it has a decimal point, use the BCMath functions.
vic at liveforspeed dot net
25-Mar-2005 12:48
I couldn't find any function to read a float from a file written by C++ (PC?) for example. This format has reversed byte order compared to PHP and in addition, there is just no bin2float function afaik, so I wrote my own binary float 2 usable php float import function.
It does not support SNaN and QNaN values though (didn't need to check for them for my purpose).
Hope it'll be to some use for some:
<?
function bin2float ($bin) {
$float = (float) 0;
$exponent = ord ($bin{3});
if ($sign = $exponent & 128) $exponent -= 128;
$exponent <<= 1;
$fraction = (float) 1;
$div = 1;
for ($x=2; $x>=0; $x--) {
$byte = ord ($bin{$x});
for ($y=7; $y>=0; $y--) {
if ($x==2 && $y==7) {
if ($byte & (1 << $y)) $exponent += 1;
} else {
$div *= 0.5;
if ($byte & (1 << $y)) $fraction += $div;
}
}
}
if (!$exponent && $fraction == 1) return 0;
$exponent -= 127;
$float = pow (2, $exponent) * $fraction;
if ($sign) $float = -($float);
return $float;
}
echo bin2float (chr (0xb1).chr (0x5c).chr (0xbc).chr (0x41))."\n";
echo bin2float (chr (0x00).chr (0x18).chr (0x5c).chr (0x3f))."\n";
echo bin2float (chr (0).chr (0).chr (160).chr (193))."\n";
echo bin2float (chr (0).chr (0).chr (0).chr (0));
?>
returns:
23.5452594757
0.859741210938
-20
0
(to understand the workings of floats better, I found http://www.randelshofer.ch/fhw/gri/float.html to be a good reference)
edsko at edsko dot net
17-Feb-2005 04:31
The formal specification of the floating point numbers as specified above is not complete. For one thing, it is not immediately obvious which of the three rules describes "floating point numbers" (in general). The disjunction of all three perhaps? My interpretation is that a floating point number is either a DNUM or an EXPONENT_DNUM.
Moreover, the specification as stated does not allow for signs (+ or -). Yet, PHP does actually allow for signs in the specification of floating point numbers (as one would expect):
<?php
$f = (float) "-0.5";
var_dump($f); ?>
Thus, the following specification is more complete:
FLOAT [+-]?({DNUM}|{EXPONENT_DNUM})
LNUM [0-9]+
DNUM ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
EXPONENT_DNUM ( ({LNUM} | {DNUM}) [eE][+-]? {LNUM})
feline at NOSPAM dot penguin dot servehttp dot com
12-Aug-2004 06:36
General computing hint: If you're keeping track of money, do yourself and your users the favor of handling everything internally in cents and do as much math as you can in integers. Store values in cents if at all possible. Add and subtract in cents. At every operation that wii involve floats, ask yourself "what will happen in the real world if I get a fraction of a cent here" and if the answer is that this operation will generate a transaction in integer cents, do not try to carry fictional fractional accuracy that will only screw things up later.
gallico_ at hotmail dot com
07-Sep-2003 08:34
To complete the thread about testing two floating point numbers for equality, here's the way it works for *every* programming language:
<?php
$epsilon = 0.0001; if (abs($one_float - $another_float) < $epsilon)
?>
james dot cridland at virginradio dot co dot uk
28-Apr-2003 07:44
The 'floating point precision' box in practice means:
<? echo (69.1-floor(69.1)); ?>
Think this'll return 0.1?
It doesn't - it returns 0.099999999999994
<? echo round((69.1-floor(69.1))); ?>
This returns 0.1 and is the workaround we use.
Note that
<? echo (4.1-floor(4.1)); ?>
*does* return 0.1 - so if you, like us, test this with low numbers, you won't, like us, understand why all of a sudden your script stops working, until you spend a lot of time, like us, debugging it.
So, that's all lovely then.
dev at maintainfit dot com
15-Apr-2003 11:27
I was programming an accounting application in MySql that required me to sum a collection of floats and ensure that they equal zero before commiting a transaction, but as seen above a sum of floats cannot always be trusted (as was my case). I kept getting a very small remainder (like 1.4512431231e-14). Since I had used number_format(num,2) to set the precision of the numbers in the database to only two (2) decimal places, when the time comes to calculate the sum I simply multiply every number by ten (10), therby eliminating and decimal places and leaving me with integers to preform my sum. This worked great.
01-Apr-2003 02:20
In response to "...the author probably knows what they are talking about..." above:
Of course the author knows what they're talking about. The previous poster missunderstood the semantics of the author's example of the decimal representation of 1/3. The author is not suggesting that some property of decimal numbers causes the behaviour, but that the property of finite binary representations of real numbers which does cause the problem is shared by finite decimal representations. To paraphrase, the author is saying "10*(0.1+0.7) gives 7.99999... because of the binary equivalent of the fact that 1/3+2/3 gives 0.99999... when using finite decimal representations (where 1/3 == 0.33333... and 2/3 == 0.66666..., so 1/3+2/3 == (0.33333...)+(0.66666...) == 0.99999... instead of 1)."
The problem occurs with finite representations of real numbers, regardless of base of the number system used.
Theo Diem
26-Mar-2003 10:35
Just to mention ....
$something = "12.20";
$value = (float) $something;
Depending you locale settings (see setlocale) this will return a float number 12.2 or 12 (without decimal part, if you locale uses another symbol than dot for decimal part)
Be aware if u are working with PHP using one locale setting (by setlocale) and a SQL database with other locale ....
Julian Suggate
10-Mar-2003 06:22
Never never never compare floats for equality! Even a >= is asking too much of any binary computer (that's pretty much all of them ;-). It will sometimes work, but the best you can hope for is a subtle bug that will occasionally cause non-deterministic behaviour.
Floats must only ever be used for proper inequalities.
backov at spotbrokers-nospamplz dot com
05-Mar-2003 01:16
I'd like to point out a "feature" of PHP's floating point support that isn't made clear anywhere here, and was driving me insane.
This test (where var_dump says that $a=0.1 and $b=0.1)
if ($a>=$b) then echo "blah!";
Will fail in some cases due to hidden precision (standard C problem, that PHP docs make no mention of, so I assumed they had gotten rid of it). I should point out that I originally thought this was an issue with the floats being stored as strings, so I forced them to be floats and they still didn't get evaluated properly (probably 2 different problems there).
To fix, I had to do this horrible kludge (the equivelant of anyway):
if (round($a,3)>=round($b,3)) then echo "blah!";
THIS works. Obviously even though var_dump says the variables are identical, and they SHOULD BE identical (started at 0.01 and added 0.001 repeatedly), they're not. There's some hidden precision there that was making me tear my hair out. Perhaps this should be added to the documentation?
www.sarioz.com
04-Feb-2003 10:49
just a comment on something the "Floating point precision" inset, which goes: "This is related to .... 0.3333333."
While the author probably knows what they are talking about, this loss of precision has nothing to do with decimal notation, it has to do with representation as a floating-point binary in a finite register, such as while 0.8 terminates in decimal, it is the repeating 0.110011001100... in binary, which is truncated. 0.1 and 0.7 are also non-terminating in binary, so they are also truncated, and the sum of these truncated numbers does not add up to the truncated binary representation of 0.8 (which is why (floor)(0.8*10) yields a different, more intuitive, result). However, since 2 is a factor of 10, any number that terminates in binary also terminates in decimal.
27-Sep-2002 11:45
much easier:
e.g. round(3.1415927,2) => 3.14
round(1092,-2) => 1100
jeroen at php dot net
23-May-2001 07:13
If you want to round a floating point number to the nearest multiple of some number n, use the following trick:
$rounded = round($number / n) * n
For example, to round 12874.49 to the nearest 100-multiple (i.e. 12900), use
$rounded = round($number / 100) * 100
Use ceil() or floor() if you want to round down/up.
| |
| | Citas célebres | Las mujeres y los gatos hacen lo que les parece, y los hombres y los perros se relajan y se hacen a la idea. Robert L. Heinlein Escritor estadounidense (1907-1988) | | Citas en tu mail | | ©Contenidos Gratis |
| Chiste de... M閐icos | | Milagros | - ¡Este doctor hace verdaderos milagros! Curó a mi mujer en tres segundos.
- ¡No es posible!
- Pues sí: le dijo que todas sus enfermedades no eran mas que síntomas de la proximidad de la vejez. | | Chistes en tu mail | | ©ContenidosGratis |
| Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos |  | Cake Mania Jugadores: 6835 Categoría del juego: Acción Objetivo del juego: Ayuda a Jill a recuperar la pasteler韆 de su abuela llevando su propia pasteler韆; consigue clientes y gana dinero. |
|  | Rainbow Web Jugadores: 2199 Categoría del juego: Puzzles Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantas韆 en Rainbow Web. Tendr醩 toneladas de diversi髇 mientras juegas a este m醙ico desaf韔 para la mente. |
|  | Mahjongg Fortuna Jugadores: 12462 Categoría del juego: Solitarios Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta. |
|  | Chainz 2 Jugadores: 6955 Categoría del juego: Puzzles Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del a駉 pasado, Chainz. Gira eslabones y crea combinaciones de 3 m醩. |
|  | Delicious Jugadores: 4405 Categoría del juego: Acción Objetivo del juego: 縀res un as de la multitarea? 縌uieres que tus clientes est閚 contentos? ues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; o te arriesgues! |
|  | Bookworm Jugadores: 4568 Categoría del juego: Palabras Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos! |
|  | Zuma Jugadores: 4976 Categoría del juego: Acción Objetivo del juego: Controla el 韉olo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acci髇. ispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morir醩! |
|  | Jewel of Atlantis Jugadores: 3798 Categoría del juego: Puzzles Objetivo del juego: Descubre la ciudad hundida de la Atl醤tida y busca valiosos tesoros. Viaja m醩 all de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis. |
|  | Jewel Quest Jugadores: 3727 Categoría del juego: Puzzles Objetivo del juego: Convierte la arena de la antigua selva en oro tan r醦ido como puedas juntando grupos de 3 elementos. os grupos m醩 grandes valen m醩 puntos! |
|  | Bejeweled 2 Jugadores: 3659 Categoría del juego: Puzzles Objetivo del juego: Con cuatro modos de juego 鷑icos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho m醩 adictivo que nunca. |
|
|