`

Ruby取精度

阅读更多
取精度,我们用了
eval(sprintf("%.3f",flaot_params))


实际情况
require 'benchmark'

times = 1000000
float = 9.234234765765765764
Benchmark.bm do |r|
  r.report('SPf  :') {
    times.times do
      f1 = sprintf('%.2f' ,float).to_f
    end
  }
  r.report('*100 :') {
    times.times do
      f2 = (100 * float).round/100.0
    end
  }
  r.report('*.01 :') {
    times.times do
      f3 = (100 * float).round*0.01
    end
  }
end

#        user     system      total        real
#SPf  :  5.590000   0.050000   5.640000 (  5.720373)
#*100 :  3.760000   0.040000   3.800000 (  3.829771)
#*.01 :  1.770000   0.010000   1.780000 (  1.811917)


round 和 sprintf的API说明:
引用

rand(max=0) => number

Converts max to an integer using max1 = max.to_i.abs. If the result is zero, returns a pseudorandom floating point number greater than or equal to 0.0 and less than 1.0. Otherwise, returns a pseudorandom integer greater than or equal to zero and less than max1. Kernel::srand may be used to ensure repeatable sequences of random numbers between different runs of the program. Ruby currently uses a modified Mersenne Twister with a period of 2**19937-1.

还有一些相关的东西:

number_with_precision(50/3,5)
#=>16.00000

number_with_precision(50.0/3,5)
#=>16.66667 



Trick: Rails里的number_with_precision

引用

  format(format_string [, arguments...] ) => string
sprintf(format_string [, arguments...] ) => string

Returns the string resulting from applying format_string to any additional arguments. Within the format string, any characters other than format sequences are copied to the result. A format sequence consists of a percent sign, followed by optional flags, width, and precision indicators, then terminated with a field type character. The field type controls how the corresponding sprintf argument is to be interpreted, while the flags modify that interpretation. The field type characters are listed in the table at the end of this section. The flag characters are:

  Flag     | Applies to   | Meaning
  ---------+--------------+-----------------------------------------
  space    | bdeEfgGiouxX | Leave a space at the start of
           |              | positive numbers.
  ---------+--------------+-----------------------------------------
  (digit)$ | all          | Specifies the absolute argument number
           |              | for this field. Absolute and relative
           |              | argument numbers cannot be mixed in a
           |              | sprintf string.
  ---------+--------------+-----------------------------------------
   #       | beEfgGoxX    | Use an alternative format. For the
           |              | conversions `o', `x', `X', and `b',
           |              | prefix the result with ``0'', ``0x'', ``0X'',
           |              |  and ``0b'', respectively. For `e',
           |              | `E', `f', `g', and 'G', force a decimal
           |              | point to be added, even if no digits follow.
           |              | For `g' and 'G', do not remove trailing zeros.
  ---------+--------------+-----------------------------------------
  +        | bdeEfgGiouxX | Add a leading plus sign to positive numbers.
  ---------+--------------+-----------------------------------------
  -        | all          | Left-justify the result of this conversion.
  ---------+--------------+-----------------------------------------
  0 (zero) | bdeEfgGiouxX | Pad with zeros, not spaces.
  ---------+--------------+-----------------------------------------
  *        | all          | Use the next argument as the field width.
           |              | If negative, left-justify the result. If the
           |              | asterisk is followed by a number and a dollar
           |              | sign, use the indicated argument as the width.

The field width is an optional integer, followed optionally by a period and a precision. The width specifies the minimum number of characters that will be written to the result for this field. For numeric fields, the precision controls the number of decimal places displayed. For string fields, the precision determines the maximum number of characters to be copied from the string. (Thus, the format sequence %10.10s will always contribute exactly ten characters to the result.)

The field types are:

    Field |  Conversion
    ------+--------------------------------------------------------------
      b   | Convert argument as a binary number.
      c   | Argument is the numeric code for a single character.
      d   | Convert argument as a decimal number.
      E   | Equivalent to `e', but uses an uppercase E to indicate
          | the exponent.
      e   | Convert floating point argument into exponential notation
          | with one digit before the decimal point. The precision
          | determines the number of fractional digits (defaulting to six).
      f   | Convert floating point argument as [-]ddd.ddd,
          |  where the precision determines the number of digits after
          | the decimal point.
      G   | Equivalent to `g', but use an uppercase `E' in exponent form.
      g   | Convert a floating point number using exponential form
          | if the exponent is less than -4 or greater than or
          | equal to the precision, or in d.dddd form otherwise.
      i   | Identical to `d'.
      o   | Convert argument as an octal number.
      p   | The valuing of argument.inspect.
      s   | Argument is a string to be substituted. If the format
          | sequence contains a precision, at most that many characters
          | will be copied.
      u   | Treat argument as an unsigned decimal number. Negative integers
          | are displayed as a 32 bit two's complement plus one for the
          | underlying architecture; that is, 2 ** 32 + n.  However, since
          | Ruby has no inherent limit on bits used to represent the
          | integer, this value is preceded by two dots (..) in order to
          | indicate a infinite number of leading sign bits.
      X   | Convert argument as a hexadecimal number using uppercase
          | letters. Negative numbers will be displayed with two
          | leading periods (representing an infinite string of
          | leading 'FF's.
      x   | Convert argument as a hexadecimal number.
          | Negative numbers will be displayed with two
          | leading periods (representing an infinite string of
          | leading 'ff's.

Examples:

   sprintf("%d %04x", 123, 123)               #=> "123 007b"
   sprintf("%08b '%4s'", 123, 123)            #=> "01111011 ' 123'"
   sprintf("%1$*2$s %2$d %1$s", "hello", 8)   #=> "   hello 8 hello"
   sprintf("%1$*2$s %2$d", "hello", -8)       #=> "hello    -8"
   sprintf("%+g:% g:%-g", 1.23, 1.23, 1.23)   #=> "+1.23: 1.23:1.23"
   sprintf("%u", -123)                        #=> "..4294967173"




1
0
分享到:
评论

相关推荐

    欧拉公式求圆周率的matlab代码-Project-Euler-Ruby:用Ruby编程语言编写的针对Euler项目的解决方案

    这些方法在专门计算圆周率的库中更为常见,比如在Ruby中可以使用`Math::PI`直接获取π的高精度值,或者使用专门的π计算库。 在提供的"Project-Euler-Ruby-master"压缩包中,虽然标题提到MATLAB代码,但标签表明这...

    RubyTapas:我在Ruby Tapas库中的工作

    2. **大整数文字** (Large integer literals): Ruby允许使用大整数文字,如`9999999999999999999999999999999999999999999999999999999999`,这些整数可以自动处理溢出,使用任意精度的数学运算。 3. **字符字面量*...

    精选常见mysql五十五道面试题目

    6. FLOAT和DOUBLE的区别在于存储精度和字节数,FLOAT有8位精度,4个字节,而DOUBLE有18位精度,8个字节。 7. CHAR_LENGTH返回字符数,考虑字符集;LENGTH返回字节数,不受字符集影响。 8. InnoDB支持的四种事务...

    SQL优化面试专题及答案.pdf

    15. **MySQL驱动程序**:MySQL提供了多种语言的驱动,如PHP、JDBC、ODBC、CWRAPPER、PYTHON、PERL、RUBY等,用于连接和操作数据库。 16. **TIMESTAMP与UPDATE CURRENT_TIMESTAMP**:TIMESTAMP列在创建时若使用...

    MySQL面试题及答案.pdf

    在 MySQL 中,自增主键的行为取决于表类型。如果表类型是 MyISAM,那么自增主键的最大 ID 会记录到数据文件中,即使重启 MySQL 也不会丢失。但是,如果表类型是 InnoDB,那么自增主键的最大 ID 只记录到内存中,重启...

    MySQL面试题,经典

    1. **自增主键**:在 MySQL 中,自增主键在表删除后是否重新使用已删除的 ID 取决于存储引擎。MyISAM 会在重启后从上次的最大值继续计数,而 InnoDB 则会记住最后一次自增值,即使删除记录,重启后也会从这个值继续...

    去BAT面试完的Mysql面试题总结(55道,带完整答案)1

    9、ENUM是预定义值集合,用于限制列只能取这些预定义的值。例如,创建一个size表,name列为 ENUM('Small', 'Medium', 'Large')。 10、REGEXP是正则表达式匹配,可以在字符串的任何位置进行模式匹配。 11、CHAR是...

    2023-MySQL面试必备新30题及答案

    在 MySQL 中,自增主键的最大 ID 的处理方式取决于表的存储引擎类型。如果表的类型是 MyISAM,那么自增主键的最大 ID 会被记录到数据文件中,重启 MySQL 也不会丢失。如果表的类型是 InnoDB,那么自增主键的最大 ID ...

    MySQL面试题及答案.docx

    在 MySQL 中,自增主键的最大 ID 的行为取决于表的类型。如果表的类型是 MyISAM,那么自增主键的最大 ID 会被记录到数据文件中,即使重启 MySQL 也不会丢失。但是,如果表的类型是 InnoDB,那么自增主键的最大 ID ...

    MySQL的面试题集锦

    FLOAT 是以 8 位精度存储浮点数,占用 4 个字节,而 DOUBLE 是以 18 位精度存储浮点数,占用 8 个字节。 CHAR_LENGTH 和 LENGTH 如何区分 CHAR_LENGTH 和 LENGTH?CHAR_LENGTH 是字符数,而 LENGTH 是字节数。...

    202311月最新MySQL-71到精选面试题题及答案涵编程题和存储知识点-20231120.pdf

    20. **MySQL服务器性能**:MySQL的性能取决于许多因素,包括硬件配置、存储引擎选择、索引优化、查询优化、事务管理和并发控制策略等。 这些知识点覆盖了MySQL的基础概念、数据类型、查询语句、存储引擎、事务处理...

    为什么大多数大型网站不是用Java写的.rar

    在IT行业中,编程语言的选择对一个项目的成功至关重要。...这取决于他们的性能需求、开发效率、生态系统的丰富程度、成本效益以及业务的具体需求。每个项目都有其独特性,因此选择最适合的工具是关键。

    史上最全55道MySQL面试题.docx

    1. **自增主键和重启**: MySQL 中,自增主键的值取决于表的存储引擎。在 MyISAM 中,自增主键的最大值存储在数据文件中,即使删除记录,重启后也会从上次的值继续增加,所以插入新记录时ID将是18。而在 InnoDB 中,...

    高频的50个 MySQL 面试题含详细讲解

    1. **自增主键的处理**:在MySQL中,自增主键的处理取决于表的存储引擎。如果表是MyISAM,删除记录后重启MySQL,插入的新记录ID将是18,因为MyISAM会将最大ID写入数据文件。而对于InnoDB,如果删除了记录并重启,新...

    MySQL面试题大全最新版

    9. **ENUM的用法**:ENUM用于限制字段只能取预定义的一组值,例如`ENUM('Small', 'Medium', 'Large')`。 10. **REGEXP**:在MySQL中,REGEXP用于模式匹配,可以在字符串的任何位置查找匹配模式。 11. **CHAR与...

    精选大厂MySQL面试题

    6. **FLOAT与DOUBLE的区别**:FLOAT存储8位精度的浮点数,占用4个字节,而DOUBLE存储18位精度的浮点数,占用8个字节。 7. **CHAR_LENGTH与LENGTH的区别**:CHAR_LENGTH返回字符串的字符数,LENGTH返回字符串的字节...

    MySQL55题及答案.pdf

    9. **ENUM的使用**:ENUM是一种预定义值列表的字符串类型,常用于限制字段只能取预设的几个值,例如`ENUM('Small', 'Medium', 'Large')`。 10. **REGEXP的定义**:REGEXP是正则表达式匹配,它可以在搜索值的任何...

    Mysql基础面试题及解答

    9. **ENUM的用法**:ENUM是预定义值列表的数据类型,用于限制字段只能取这些预定义的值,例如`ENUM('Small', 'Medium', 'Large')`。 10. **REGEXP的定义**:REGEXP是正则表达式匹配,在MySQL中用于在数据中查找匹配...

    geo:智利的 GeoJSON 数据

    GeoJSON 格式的智利取自 要将 shapefile 对象转换为 GeoJSON 使用 ogr2ogr -f GeoJSON -t_srs crs:84 [output].geojson [input].shp您还可以简化输入: ogr2ogr -f "GeoJSON" -t_srs crs:84 -overwrite -progress -...

Global site tag (gtag.js) - Google Analytics