The Antikythera Mechanism is a unique Greek geared device, constructed around the end of the second century BC. It is known that it calculated and displayed celestial information, particularly cycles such as the phases of the moon and a luni-solar calendar. Calendars were important to ancient societies for timing agricultural activity and fixing religious festivals. Eclipses and planetary motions were often interpreted as omens, while the calm regularity of the astronomical cycles must have been philosophically attractive in an uncertain and violent world. Named after its place of discovery in 1901 in a Roman shipwreck, the Antikythera Mechanism is technically more complex than any known device for at least a millennium afterwards. Its specific functions have remained controversial because its gears and the inscriptions upon its faces are only fragmentary. Here we report surface imaging and high-resolution X-ray tomography of the surviving fragments, enabling us to reconstruct the gear function and double the number of deciphered inscriptions. The mechanism predicted lunar and solar eclipses on the basis of Babylonian arithmetic-progression cycles. The inscriptions support suggestions of mechanical display of planetary positions, now lost. In the second century BC, Hipparchos developed a theory to explain the irregularities of the Moon's motion across the sky caused by its elliptic orbit. We find a mechanical realization of this theory in the gearing of the mechanism, revealing an unexpected degree of technical sophistication for the period.