¿Por qué la división en Ruby devuelve un entero en lugar de un valor decimal?


Por ejemplo:

9 / 5  #=> 1

Pero yo esperaba 1.8. ¿Cómo puedo obtener el resultado decimal correcto (no entero)? ¿Por qué está regresando 1 en absoluto?

Author: mu is too short, 2011-03-31

7 answers

Está haciendo división entera. Usted puede hacer uno de los números a Float añadiendo .0:

9.0 / 5  #=> 1.8
9 / 5.0  #=> 1.8
 218
Author: vees,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-24 03:17:47

Está haciendo división entera. Puedes usar to_f para forzar las cosas al modo de coma flotante:

9.to_f / 5  #=> 1.8
9 / 5.to_f  #=> 1.8

Esto también funciona si sus valores son variables en lugar de literales. La conversión de un valor a un flotador es suficiente para coaccionar toda la expresión a la aritmética de coma flotante.

 312
Author: mu is too short,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-24 03:16:25

También está el Numeric#fdiv método que puede utilizar en su lugar:

9.fdiv(5)  #=> 1.8
 151
Author: Konrad Reiche,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-24 06:13:32

Puede comprobarlo con irb:

$ irb
>> 2 / 3
=> 0
>> 2.to_f / 3
=> 0.666666666666667
>> 2 / 3.to_f
=> 0.666666666666667
 33
Author: Renaud,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-29 06:18:09

Puede incluir el módulo ruby mathn.

require 'mathn'

De esta manera, usted va a ser capaz de hacer la división normalmente.

1/2              #=> (1/2)
(1/2) ** 3       #=> (1/8)
1/3*3            #=> 1
Math.sin(1/2)    #=> 0.479425538604203

De esta manera, se obtiene la división exacta (clase Racional) hasta que se decide aplicar una operación que no se puede expresar como racional, por ejemplo Math.sin.

 22
Author: Rok Kralj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-02 12:43:18

Cambie 5 por 5.0. Tienes división entera.

 10
Author: Tyler Eaves,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-10-24 03:23:08

Fixnum#to_r no se menciona aquí, se introdujo desde ruby 1.9. Convierte Fixnum en forma racional. A continuación se presentan ejemplos de sus usos. Esto también puede dar la división exacta, siempre y cuando todos los números utilizados son Fixnum.

 a = 1.to_r  #=> (1/1) 
 a = 10.to_r #=> (10/1) 
 a = a / 3   #=> (10/3) 
 a = a * 3   #=> (10/1) 
 a.to_f      #=> 10.0

Ejemplo donde un flotador operado sobre un número racional cubre el resultado para flotar.

a = 5.to_r   #=> (5/1) 
a = a * 5.0  #=> 25.0 
 3
Author: Ucpuzz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-25 17:40:55