I set up a function that extracts the values from the 4-dimensional array by changing the Y value, and I put the values into a new array, the array should be [0,16/3,0,4/3],but the array is not what I want, and I want to know what’s wrong with my code
#
edge=[[0,1,1,1],[3,-14,4,1],[0,6,4,4],[3,-2,4,1]]
num=4
Infinity=1.0/0
def get_point(y,num,edge)
k=0
b=1
y_max=2
y_min=3
x=[ ]
num.times do |i|
if (y<=edge[i][y_max])&&(y>=edge[i][y_min])
if edge[i][k]==Infinity
x[i]=edge[i][k]
elsif edge[i][k]==0
x[i]=edge[i][b]
else
x[i]=(y-edge[i][b])/edge[i][k]
end
else
x[i]=0
end
end
p x
end
get_point(2,num,edge)
You were using integer math.
#
edge=[[0.0,1.0,1.0,1.0],[3.0,-14.0,4.0,1.0],[0.0,6.0,4.0,4.0],[3.0,-2.0,4.0,1.0]]
num=4
Infinity=1.0/0
def get_point(y,num,edge)
k=0
b=1
y_max=2
y_min=3
x=[ ]
num.times do |i|
if (y <= edge[i][y_max])&&(y >= edge[i][y_min])
if edge[i][k]==Infinity
x[i]=edge[i][k]
elsif edge[i][k]==0
x[i]=edge[i][b]
else
x[i]=Rational(y-edge[i][b], edge[i][k])
end
else
x[i]=0
end
end
return x
end
result = get_point(2,num,edge)
1 Like
To expand on sWilliam’s excellent answer,
Ruby is a dynamically typed language, every data object has a type even if you have not explicitely specified whether to use an Integer of a Float. It can be confusing that 1.0
and 1
are shorthand literals for Float(1.0)
and Integer(1)
.
If you cannot rely on that the input is correctly typed (e.g. input provided by someone else), and if you don’t want to convert and sanitize the input first (like edge = edge.map{ |list| list.map{ |n| n.to_f }}
), you can at least force the quotient to be a float (edge[i][k].
to_f
). This should avoid errors of integer division in place of floating point division.
The Rational class allows to do accurate math with fractional (rational) numbers and avoid accuracy problems of floating point math. Use it if you either want to display results later again in fractional form in the user interface or if you need so high accuracy that (1/10.0)**2
cannot be treated (almost) equal to 0.010000000000000002
.
3 Likes
Thank you for your wonderful comments. I have solved the problem through your Suggestions