[julia-users] Re: Splitting a multidimensional function

2015-08-21 Thread David P. Sanders
Here is a fun and possibly useful solution (that works only on 0.4 due to 
call overloading):

https://gist.github.com/dpsanders/d8ef239ec8c78c4debee

It introduces a `MultidimFunction` type, and a macro `@multidim` that works 
as follows:

julia> @multidim f(x) = [sqrt(x[1]), 2x[2]]
MultidimFunction([(anonymous function),(anonymous function)])

julia> f([1., 2.])
2-element Array{Float64,1}:
 1.0
 4.0

julia> x = [1., 2.]
2-element Array{Float64,1}:
 1.0
 2.0

julia> f(x)
2-element Array{Float64,1}:
 1.0
 4.0

julia> f[1](x)
1.0

julia> f[2](x)
4.0

julia> y = [-1., 2.]
2-element Array{Float64,1}:
 -1.0
  2.0

julia> f[1](y)
ERROR: DomainError:
sqrt will only return a complex result if called with a complex argument.
try sqrt (complex(x))
 in sqrt at ./math.jl:144
 in anonymous at 
/Users/dsanders/.julia/v0.3/ValidatedNumerics/src/multidim/multidim_functions.jl:49

julia> f[2](y)
4.0

David.



Re: [julia-users] Re: Splitting a multidimensional function

2015-08-19 Thread Elliot Saba
You may expect the optimizer to completely omit calculating the first
element, but unfortunately for you, the negativity check before the square
root will never be optimized away, since it affects the whole program
execution and thus *shouldn't* be omitted from the compiled program, even
though you're only using the result of the second computation.

I would suggest building your functions the other way around, construct
your simpler functions, and then build your composite function out of the
simpler ones:

f1(x) = sqrt(x)
f2(x) = 2*x

f(x) = [f1(x[1]), f2(x[2])]

That should get you what you want.
-E


[julia-users] Re: Splitting a multidimensional function

2015-08-19 Thread John Myles White
Since f1(x) requires a call to f(x), there's no way for your approach to 
work in Julia. You probably should define f1(x) as sqrt(x[1]) and f2(x) as 
2 * x[2].

 -- John

On Wednesday, August 19, 2015 at 2:32:38 PM UTC-7, Nikolay Kryukov wrote:
>
> I have a problem when I try to separate the components of a 
> multidimensional function. Example:
>
> Given the 2D function of a 2D argument:
> f(x) = [sqrt(x[1]), 2*x[2]]
>
> I want to split it into two separate functions which are the components of 
> the original 2D function. I thought that the obvious solution was:
>
> f1(x) = f(x)[1]
> f2(x) = f(x)[2]
>
> The second function merely doubles the second component of its argument, 
> as it should:
> f2([2, 3])
> --> 6.0
>
> But the functions don't turn out to be completely decoupled: let's see 
> what happens when we do
>
> f2([-2, 3])
> --> ERROR: DomainError
>  in f2 at none:1
>
> Even though the second function doesn't do sqrt and doesn't even depend on 
> the first component of the argument, the first component of the original 
> function is still checked and obviously returns an error. 
>
> How do I decouple a 2D function?
>