# Integrating a gradient and matching terms automatically

I am trying to integrate a function $\nabla w(x,y)$ indefinitely knowing both components of $\nabla w(x,y)$. I have a function dw[x_,y_] that I have defined. I then use Integrate[dw[x, y][[1]], x] and Integrate[dw[x, y][[2]], y] to get my two expressions for $w(x,y)$. But now I want to match terms in each expression automatically and impose a condition to solve for the one integration constant which is independent of $x$ and $y$. The function Collect does not seem to do it. Any tips?

• Show us the function you are working with. Hard to say otherwise. – MarcoB Mar 13 '16 at 21:17
• Take $\nabla w = \{x + y,x+y,0\}$ for example. We know from calculus that we get two expressions for $w$: $w = 0.5 x^2 + yx + f(y)$ and $w = xy + 0.5 y^2 + g(x)$. I want mathematica to give me the final answer, which is $w = 0.5x^2 + xy + 0.5y^2 + C$, where $C$ is a constant independent of $x$ and $y$. – Johnver Mar 13 '16 at 21:23

Won't necessarily work in general, but just have Mathematica do the integration for you:

dw[x_, y_] = {x + y, x + y, 0};
First@DSolve[{D[f[x, y], x] == dw[x, y][[1]], D[f[x, y], y] == dw[x, y][[2]]}, f[x, y], {x, y}]
(* {f[x, y] -> x^2/2 + x y + y^2/2 + C[1]} *)


Here's a way to do it by hand. This method tests at the end for the exactness of the differential, which is nice, so I will illustrate it with an exact differential and an inexact one:

dw[x_, y_] = {x + y, x}
ws = {Integrate[dw[x, y][[1]], x] + f[y],  Integrate[dw[x, y][[2]], y] + g[x]}
sols = Join @@ {
Solve[0 == Select[Subtract @@ ws // Expand, FreeQ[#, x] &], f[y]],
Solve[0 == Select[Subtract @@ ws // Expand, FreeQ[#, y] &], g[x]]
}
SameQ @@ %


and

dw[x_, y_] = {x + y, x^2}
ws = {Integrate[dw[x, y][[1]], x] + f[y], Integrate[dw[x, y][[2]], y] + g[x]}
sols = Join @@ {
Solve[0 == Select[Subtract @@ ws // Expand, FreeQ[#, x] &], f[y]],
Solve[0 == Select[Subtract @@ ws // Expand, FreeQ[#, y] &], g[x]]
}