我如何找出Ruby中的Float大小? [英] How do I find out of what size a Float in Ruby is?

查看:54
本文介绍了我如何找出Ruby中的Float大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据文档,Ruby Float是使用本机体系结构的双精度浮点表示形式不精确的实数."

这是否意味着在32位Ruby上等效于C float ,而在64位Ruby上等效于C double ?

如果是,我如何在运行时找出程序在哪个Ruby上运行(准确地说是多少位)?它可以在任何OS和任何Ruby实现(mri ruby​​,rubinius和jruby)上运行.

我想出的解决方案:

  def architecture_bits1.尺寸* 8结尾 

在所有情况下都行得通吗?有没有更好/更优雅的方法?

解决方案

单精度/双精度浮点数的大小与您是否正在运行ruby的64/32位实现无关,因此您的实现将返回错误的信息回答关于ruby的任何32位实现.

Float定义常量,例如 Float :: MANT_DIG Float :: MAX_EXP ,您可以从中得出浮点数使用的存储量.尽管不是ieee 754双精度(53位尾数(其中存储了52位),1位符号,11位指数),这是非常罕见的.

According to the docs a Ruby Float is an "inexact real number using the native architecture's double-precision floating point representation."

Does that mean that on 32 bit Ruby they are equivalent to a C float and on 64 bit Ruby to a C double?

If yes, how do I find out which Ruby the program is running on (how many bits, to be precise) at runtime? It should work on any OS and any Ruby implementation (mri ruby, rubinius and jruby).

The solution I came up with:

def architecture_bits
  1.size * 8
end

Does that work under all circumstances? Is there a better/more elegant approach?

解决方案

The size of single/double precision floats isn't related to whether you're running 64/32 bit implementations of ruby, so your implementation will return the wrong answer on any 32 bit implementation of ruby.

Float defines constants such as Float::MANT_DIG and Float::MAX_EXP from which you can derive the amount of storage used by a float. It will be pretty uncommon for it not to be an ieee 754 double precision though (53 bit mantissa (of which 52 are stored), 1 bit sign, 11 bits exponent)

这篇关于我如何找出Ruby中的Float大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆