It becomes more obvious if you write "a += 3" as the longer form "a = a + 4"

kl. 19:57:22 UTC+1 fredag 24. januar 2014 skrev Eric Ford følgende:
>
> Sorry.  (Evidently, downloading a notebook is based on the last saved 
> version and what's currently on your screen.)  IJulia notebook attached. 
>  Readable version below.
>
> function f1(x::Array)
>  w = x  
>  w += 10.0
>  return w
> end
>
> function f2(x::Array)
>  w = x  
>  for i in 1:length(x)
>    w[i] += 10.0
>  end
>  return w
> end
>
> x=randn(10)
> x_orig = deepcopy(x)
> f1_of_x = f1(x)
> println("After f1: ",sum((x.-x_orig).^2));
> x = deepcopy(x_orig)
> f2_of_x = f2(x)
> println("After f2: ",sum((x.-x_orig).^2));
>
> After f1: 0.0
> After f2: 1000.0
>
>
> Thanks,
> Eric
>
>
>
> On Friday, January 24, 2014 1:10:59 PM UTC-5, Kevin Squire wrote:
>>
>> In what you posted,  `f1` and `f2` are identical (except for the name).  
>> Can you share the output of a Julia or IJulia session showing the problem?
>>
>> Cheers,
>>    Kevin
>>
>>
>> On Fri, Jan 24, 2014 at 9:58 AM, Eric Ford <[email protected]> wrote:
>>
>>> I don't understand why the first function doesn't change x, but the 
>>> second function does.  
>>> Is the = calling deepcopy in f1, but copy in f2?  
>>> If so, why?
>>>
>>> function f1(x::Array)
>>>  w = x  
>>>  for i in 1:length(x)
>>>    w[i] += 10.0
>>>  end
>>>  w += 10.0
>>>  return w
>>> end
>>>
>>> function f2(x::Array)
>>>  w = x  
>>>  for i in 1:length(x)
>>>    w[i] += 10.0
>>>  end
>>>  w += 10.0
>>>  return w
>>> end
>>>
>>> x=randn(10)
>>> x_orig = deepcopy(x)
>>> f_of_x = f(x)
>>> sum((x.-x_orig).^2)
>>>
>>> After f1: 0.0
>>> After f2: 1000.0
>>>
>>> Thanks,
>>> Eric (on behalf of an Astro 585 student)
>>>
>>>
>>

Reply via email to