Why Julia is giving a different answer than r?

i have a simple equation as given below (julia code). I’m getting different answer as compare to r. Am I missing something?

x=100
y=0
d = 20
h = -2
c = [0, 1, 2, 3, 4, 5]
A = x .+ ((y - x) / (1 .+ (c / d).^h))

answer in r : 100.00000 99.75062 99.00990 97.79951 96.15385 94.11765
answer in julia: NaN 100.0 100.0 100.0 100.0 100.0

The code that you’ve presented isn’t runnable. I’ve fixed it here, and the answer seems to match that from R:

julia> x=100;

julia> y=0;

julia> d = 20;

julia> h = -2;

julia> c = [0, 1, 2, 3, 4, 5];

julia> A = x .+ ((y - x) ./ (1 .+ (c / d).^h))
6-element Vector{Float64}:
 100.0
  99.75062344139651
  99.00990099009901
  97.79951100244499
  96.15384615384616
  94.11764705882354
2 Likes

I’d suggest using @. It makes it easier to avoid excess allocations, e.g. c / d should be c ./ d.

2 Likes

I agree, this is often better:

julia> A = @. x + ((y - x) / (1 + (c / d)^h))
6-element Vector{Float64}:
 100.0
  99.75062344139651
  99.00990099009901
  97.79951100244499
  96.15384615384616
  94.11764705882354
2 Likes

Thanks a lot for help and suggestions. :slightly_smiling_face:

The original code with the missing dot runs on Julia 1.8 but the number/vector method was removed in 1.9: Remove number / vector by antoine-levitt · Pull Request #44358 · JuliaLang/julia · GitHub precisely to avoid this type of mistake :slight_smile:

7 Likes