VBA Help

I cant get the number 2 to display properly.

Problem: Write a VBA function to solve for f(x) for different values of x ranging from 0 to 2 with increments of 0.1.

I called a cell I for increment of .1, then used “=cell+i” for 0-2.1. For some reason 2 displays as out of range. I was told its because of ‘phantom digits’ when using non integer values and a solution is to use for loops and integers with division. There has to be a solution using if statements though.

Function hw_3(x)

If x >= 0 And x <= 0.5 Then
hw_3 = 1.2 * x ^ 2
ElseIf x > 0.5 And x < 1.2 Then
hw_3 = 1 - ((1 / 12) * (x - 0.5))
ElseIf x >= 1.2 And x <= 2 Then
hw_3 = Exp(-2 * x)
ElseIf x < 0 Or x > 2 Then
hw_3 = “out of range”
End If

End Function

Any ideas? I can submit it as is since its a known issue so I’m just looking for an solution out of curiosity.

---------- Post added at 01:47 PM ---------- Previous post was at 01:42 PM ----------

I wrote it with an if statement inside of a cell and it worked. wtf.

=IF(AND(B19>=0,B19<=0.5),1.2*(B19)^2,(IF(AND(B19>0.5,B19<1.2),1-(1/12)(B19-0.5),IF(AND(B19>=1.2,B19<=2),EXP(-2B19),“out of range”))))

What if you try adding:

ElseIf x = 2 Then
hw_3 = Exp(-2 * x)

I’m no programmer, just throwing it out there.

what happens with .2?

Should equal 0.048 correct?

well, I don’t realy care what the end result is…The way he defined the condition in the first part is basically the same as the part he’s having trouble with. Just wanted to make sure that was working.

---------- Post added at 03:52 PM ---------- Previous post was at 03:51 PM ----------

actually, what I really meant, is what happens with .5?

I tried it, doesn’t change anything

see picture

.5 is caught with the first line since its <= .5 (which means less than or equal to) but NOT the second line because it is just <.5

what about changing:

ElseIf x < 0 Or x > 2.1 Then
hw_3 = “out of range”