Can two functions with different codomains be equal?
It can be convenient to require that codomains are part of the definition of a function. For example, when speaking of surjectiveness: If $f=g$ and $f$ is surjective, then $g$ is surjective, but only if we are careful to require that equality implies having the same target set.
The first function you defined is not surjective. The second one is, and in fact it is invertible.
Similarly, the inclusion $\mathbb Z\to\mathbb R$ is for some purposes different from the identity map $\mathbb Z\to\mathbb Z$.
It is true that in many contexts it hardly matters. You might be interested in this MathOverflow question coming from a case where the distinction was considered important.