University College London experts have shown how the brain subconsciously remembers details around past dangers.
The researchers scanned people's brains to monitor activity
Writing in Nature, they say blocking this system could help treat pain by interrupting such a brain process.
Researchers said volunteers could not recall details of a test which had led to them getting a mild electric shock.
But activity in the brain revealed that they had correctly logged the data by using a series of complicated computations.
Fourteen patients were given a half-hour test while lying in a functional magnetic resonance brain scanner - tests were done by researchers at the Wellcome Department of Imaging Neuroscience at UCL.
They were shown a series of abstract pictures followed by a one-second electric shock - equivalent to a pin-prick.
When the tests were completed many of the volunteers could not recall the sequence of images.
But the scanner revealed that two key areas, the ventral striatum and part of the cerebral cortex, were working together to figure out what was coming next.
Dr Ben Seymour, who led the research, said: "If we showed a square followed by a circle followed by the painful shock this part of the brain could soon learn to predict that the circle was bad news.
"However, after a while, it would learn that the square wasn't that good either, as it was followed by the circle.
"By recording these chains of events, the brain was able to set early alarm bells ringing in the volunteer."
He added: "The brain is a phenomenal biological computer with around 100 billion nerve cells which determine our thoughts and behaviour.
"Evolution clearly favours animals that are good at looking after themselves.
"Although we may not always be aware of it, the brain tries to ensure our self-preservation through a complex mathematical strategy.
"We have shown how it works out what are potentially dangerous or painful episodes by interpreting chains of events and basically assessing the odds.
"Imagine you are bitten by your neighbour's dog," he said. "You soon learn not only to avoid the dog, but also things associated with it like its favourite haunts."
He hopes that further research into the brain's computational skills could eventually help many people who suffer ongoing pain - which affects about 10% of the UK population at some time in their lives.
"Although chronic pain is relatively common, it remains poorly understood and often remarkably difficult to treat," he added. "