Major oil companies use secret mathematical formulas to figure out the varying price of gas from one city to city – even as specific as one neighborhood to another.

Gas stations owned by large oil companies, such as ExxonMobil, determine the cost of gas by creating “geographic pricing zones” based on competition from nearby pumps, traffic patterns and the makeup of the local population.

Oil companies claim they use the formulas to confine competition to the smallest possible area in order to maximize prices at each outlet.

But independently owned stations set their prices based on the owner’s assessment – factoring in how much it costs to buy the gas from a distributor and the price of his nearest competitors.

“It depends on what a particular station pays for gas and how much overhead they have,” said Cathy Kenny, a lobbyist with the New York State Petroleum Council.

Larger outlets, such as Costco, buy more gas and as a result pay less for it. Smaller stations buy less of it and raise their prices to try and pull in a profit.

The cost of crude itself accounts for about half the retail price at the pump. The rest of the cost is for refining, shipping, taxes and the cost of running the station.

But why does gas cost so much in Manhattan compared to Staten Island?

“There are fewer gas stations in Manhattan,” Kenny said. “And there’s even fewer of them since owners figured out that selling the land is a lot more profitable than selling gas.”

This past weekend, the priciest place to get gas in the city was at a Shell station in Brooklyn and an Exxon station on Staten Island, both of which were charging $4.25, according to newyorkgasprices.com.

The cheapest, too, was on Staten Island, where Costco pumped regular for $3.91 – up two cents from the $3.89 reported online earlier in the day.