How to generate a range of floating-point numbers in Ruby

3 Answers

0 votes
# ==================================================
# Title: Generate a Range of Floating-Point Numbers
# ==================================================
#
# Best Practice:
# - Use an integer loop counter.
# - Calculate each floating-point value from the index.
# - Avoid repeatedly adding the step value because
#   floating-point rounding errors can accumulate.

start = 0.0
step = 0.1
count = 11 # Generates values from 0.0 through 1.0 inclusive.

# Use an integer-controlled loop.
#
# Each value is calculated independently:
#
#   start + index * step
#
# This approach is more reliable than:
#
#   value += step
#
count.times do |i|
  value = start + (i * step)

  # Format output to one decimal place.
  puts format("%.1f", value)
end


# run:
#
# 0.0
# 0.1
# 0.2
# 0.3
# 0.4
# 0.5
# 0.6
# 0.7
# 0.8
# 0.9
# 1.0
#

 



answered Oct 7 by avibootz
0 votes
# ==================================================
# Title: Reusable Floating-Point Range Method
# ==================================================
#
# This method:
# - Validates input arguments
# - Returns an Array of Float values
# - Uses integer-based iteration
# - Avoids cumulative floating-point errors

def generate_range(start_value, end_value, step_size)
  # Validate arguments.
  raise ArgumentError, "step_size must be positive" if step_size <= 0.0

  raise ArgumentError,
        "end_value must be greater than or equal to start_value" \
        if end_value < start_value

  # Calculate the number of values to generate.
  count = ((end_value - start_value) / step_size).floor + 1

  values = []

  count.times do |i|
    values << start_value + (i * step_size)
  end

  values
end

values = generate_range(0.0, 1.0, 0.1)

values.each do |value|
  puts format("%.1f", value)
end


# run:
#
# 0.0
# 0.1
# 0.2
# 0.3
# 0.4
# 0.5
# 0.6
# 0.7
# 0.8
# 0.9
# 1.0
#

 



answered Oct 7 by avibootz
0 votes
# ==================================================
# Title: Enumerable-Based Solution
# ==================================================
#
# Ruby's Enumerable methods allow us to
# express the range generation cleanly.

start = 0.0
step = 0.1
count = 11

values =
  (0...count).map do |i|
    start + (i * step)
  end

puts values.inspect


# run:
#
# [0.0, 0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6000000000000001, 0.7000000000000001, 0.8, 0.9, 1.0]
#

 



answered Oct 7 by avibootz

Related questions

...