What is the default float step in Ruby?

In Ruby, this code compiles:

(Math::PI * 6 .. Math::PI * 6.5).bsearch{|f| Math.cos(f) <= 0.5}

What is the default for the range in this case?

+4
source share
1 answer

In your case there is no step. Floating-point ranges cannot be repeated.

The code

(Math::PI * 6 .. Math::PI * 6.5).to_a

throws a TypeError:

TypeError: Unable to retry with Float


Your code is valid because it bsearchdoes not iterate over the range values. Instead, it “knows” the values ​​of min and max and half the interval until it reaches the value for which the block { |f| Math.cos(f) <= 0.5 }returns true.

, puts , bsearch:

(Math::PI * 6 .. Math::PI * 6.5).bsearch { |f| puts f; Math.cos(f) <= 0.5 }
+6

Source: https://habr.com/ru/post/1570052/


All Articles