It may be a long way off, but there's no doubt about it: our galaxy is heading for an epic mash-up with the neighbouring galaxy Andromeda.

Thanks to the precise measurements that the Hubble Space Telescope's deep views of space allow astronomers to make, they can now say with certainty that the Milky Way will smash into the galaxy, which is also known as M31, in about four billion years.

"After nearly a century of speculation about the future destiny of Andromeda and our Milky Way, we at last have a clear picture of how events will unfold over the coming billions of years," said Sangmo Tony Sohn of the Space Telescope Science Institute in Baltimore in a press release issued by NASA and the institute on Thursday.

See into the future

Watch NASA's simulation video of the collision of Andromeda and the Milky Way.

Andromeda may still be 2.5 million light-years from the Milky Way, but the pull of gravity between the two galaxies and the dark matter around them ensures that it will collide with our galaxy and eventually merge with it.

That merging process will take another two billion years after the collision, during which time stars will reorder themselves into new orbits around the fused galaxy's new galactic centre.

Andromeda will be travelling about 400,000 kilometres per hour when it hits our galaxy, but the collision won't harm Earth or our solar system since each galaxy's stars are far enough apart to avoid smashing into each other. It will, however, knock the sun into a new part of the galaxy.

"In the 'worst-case-scenario' simulation, M31 slams into the Milky Way head-on, and the stars are all scattered into different orbits," said Gurtina Besla of Columbia University in New York, who was part of the team that studied the sideways motion of M31 to determine whether it would, indeed, hit the Milky Way.

"The stellar populations of both galaxies are jostled, and the Milky Way loses its flattened pancake shape with most of the stars on nearly circular orbits. The galaxies' cores merge, and the stars settle into randomized orbits to create an elliptical-shaped galaxy."

Andromeda will also be travelling with a smaller galaxy, known as Triangulum, or M33, which might end up hitting the Milky Way first and possibly also merge with the two larger galaxies.

Astronomers had been trying to precisely measure M31's sideways motion for more than a century and until now were not sure whether galaxy would just nick the Milky Way, crash into it or avoid it altogether. By repeatedly observing select regions of Andromeda over a five- to seven-year period, they were able to nail down how the two galaxies will interact.

The recent findings will be reported in several papers in the Astrophysical Journal.