Добавить новость
ru24.net
Все новости
Июнь
2024

Hero coder finds bug in Lunar Lander after 55 years—'I suspect everybody else was just happy to play the game and have fun'

0
 Hero coder finds bug in Lunar Lander after 55 years—'I suspect everybody else was just happy to play the game and have fun'

"Digging in, I was amazed by the sophisticated physics and numerical computing in the game."

Apollo 11 touched down on the moon's surface on July 20, 1969, an achievement for all humankind that put a full stop on the first iteration of the space race. Neil Armstrong stepped into history as the globe watched and among the millions in awe was 17 year-old schoolboy Jim Storer. 

Based in Massachusetts and with a considerable grounding in mathematics, thanks partly to his physicist father, Storer was inspired by the very concept of a moon landing: the precise calculations and control required to safely bring a huge chunk of aluminium to rest on a barren, unfamiliar surface. Storer's school had a PDP-8, the first commercially successful minicomputer, and the young man set about writing a new program called "Lunar Landing Game".

Text-based and written in the early programming language FOCAL, Lunar Landing Game would ask the player for instructions on each turn, with the height, velocity, and remaining fuel of the lander calculated over each in-game second of the descent. Essentially it's a game about using your fuel supply to slow and control the craft's descent, and when the craft reaches the surface the player gets a report on their landing speed and remaining fuel. 

The whole game is less than 50 lines of code, but its apparent simplicity belied the calculations underlying the simulation, and over the years the game became widely popular as a programming challenge. Even later, various popular commercial versions would add a visual layer (to give an idea of its longevity, Atari is currently in the process of developing an official sequel).

Software engineer Martin C. Martin has announced in a new blogpost that, while playing around with the original game's code, he found and fixed a bug that's lain dormant over the 55 years since the game was coded (first spotted by Ars Technica). Now retired, Martin's had a stellar career at the likes of Rockstar, Meta, and as a postdoc research fellow at MIT, and is exactly the type of individual who looks at something like Lunar Lander and decides to work out the optimal strategy for a perfect landing.

"I recently explored the optimal fuel burn schedule to land as gently as possible and with maximum remaining fuel," writes Martin. "Surprisingly, the theoretical best strategy didn’t work. The game falsely thinks the lander doesn’t touch down on the surface when in fact it does. Digging in, I was amazed by the sophisticated physics and numerical computing in the game. Eventually I found a bug: a missing 'divide by two' that had seemingly gone unnoticed for nearly 55 years."

Suicide burn

That is, Martin's perfect strategy wasn't being registered by the game as a successful landing. The coder was using what Kerbal Space Program players call the "suicide burn", whereby you maximise speed by not using fuel, then burn full-throttle at the last moment to reduce the speed to as close to zero just before you hit the surface.

"With some trial and error and a bit of (manual) binary search, you can find the schedule that just barely has you landing. You burn nothing for 70 seconds, then 164.31426784 lbs/sec for the next 10 seconds, then the max 200 lbs/sec after that," writes Martin.

"The game considers a perfect landing to be less than 1 MPH, but here we land at over 3.5 MPH and are told we 'could be better.' Yet burn even 0.00000001 more lbs/sec, and you miss the surface entirely, ascending at 114 MPH:

"How did we go from a hard landing to not landing at all, without a soft landing in between?"

When the coder started looking into why, he found that rather than "the simple Euler integration that's common in video games even today", underpinning the game's logic were more sophisticated equations: "Jim [Storer] used the exact solution, the Tsiolkovsky rocket equation, with a Taylor series expansion for the logarithm," writes Martin. "He also used some algebra to simplify it and reduce the amount of round off error. Very impressive for a high school senior in 1969."

Martin contacted Storer to confirm what he'd found, and ask about where this sophisticated math had come from. "I was skilled at calculus at the time and familiar with concepts like a Taylor series," says Storer, "but also my recollection is that my father, who was a physicist, helped me in the derivation of the equations."

Either way, the the rocket equation is what should make the suicide burn optimal, and the accuracy of the Taylor series suggests that's not the issue either. Instead the problem was contact: the moment where the Lander lands.

"Imagine the lander descending at the start of a 10-second turn but ascending by the end," writes Martin. "Simply verifying that it’s above the surface at both points isn’t enough. It might have dipped below the surface somewhere in between. When this happens, the program has to rewind and examine an earlier moment."

As Martin goes on to explain, the error creeps in when the game is trying to approximate the bottom of the trajectory. The coder presents his full working out in the blog post but, essentially, it comes down to Storer using an alternate form of a quadratic formula where for whatever reason "he’s missing the 2 in the denominator inside the square root! It was probably a simple error, either when deriving the formula or typing it into the computer." As Martin is careful to point out, Storer wouldn't have had access to algebra software and was doing this all with pencil and paper.

The missing "2" means that the game "consistently underestimates the time to the lowest point", which it then compensates for by adding a fraction of time (0.05 sec) and re-estimating. "And this explains why it misses the time of landing: the first estimate is while the lander is above the surface and still descending, then the second one is after reaching the bottom and ascending again, which takes less than 0.05 sec."

Martin goes on to explain the effect of fixing the bug, and spitball about some of the reasoning. Though he does note sadly that, even with the bug fixed, there are some optimal landing strategies but "the theoretical full-thrust-on-landing suicide burn, that takes around 148 seconds, eludes us."

Martin ends by paying tribute to the sophistication of Lunar Landing Game, coded in 1969 by a high-school student, and incorporating aspects of numeric computing that "I didn't learn until I was studying for a Ph.D. in robotics."

As for a bug surviving in a piece of popular software for 55 years?

"That’s probably because, even with the bug, it was a fun game, both difficult and possible to land gently," writes Martin. "The quest to not just win, but find the optimal strategy, can certainly lead to trying to understand small discrepancies. I suspect everybody else was just happy to play the game and have fun."

If you're interested in the history of Lunar Lander, this 40th anniversary retrospective speaks to Storer himself about the game's creation. And if you just like old bugs, here's a doozy: the developer who returned to his game after four decades, then found and fixed a typo so it actually worked.




Moscow.media
Частные объявления сегодня





Rss.plus



Заместитель генерального директора ГПМ Радио по дистрибуции и технологиям отмечен наградой «Медиа-Менеджер России – 2024»

МЕТЕОРИТ БОЛЬШЕ СИРИУСА? КАК НАЛАДИТЬ КОСМОС. Советы Высшего Всенародного Президента.

Пожар в центре Москвы локализован на площади 600 квадратных метров

Куда сходить москвичам и гостям столицы 13 июля - Мытищинский форсаж: часть вторая


Лучшие аппараты для лазерной эпиляции: выбираем идеальный вариант

Россиянам предложили новый вид отдыха в Турции

Дирекция по качеству АО "Желдорреммаш" посетила локомотивостроительные заводы ТМХ

Йошкар-Ола готовит будущих чемпионов по фитнес-аэробике РФ


‘I made it work that night’: Stevenson reflects on negative fan response as he readies for next outing

Portugal vs France – Euro 2024: Ronaldo and Mbappe have one last dance in quarter-final tie – stream FREE, TV, team news

Leeloo Dolls: Your Premier Destination for Realistic Sex Dolls

An iconic Michael Jordan photo will be on Tyler Reddick's car as he races through Chicago


Родные просторы... Старая Устьевская ГЭС на реке Вруда

Языковые модели на основе искусственного интеллекта, повышение производительности сотрудников и экономия ресурсов: BIA Technologies обозначила основные тренды цифровой трансформации

Столичный спецназ Росгвардии завершил полевой выход в Подмосковье

Военные следователи провели в Ялте проверку лиц, не вставших на воинский учет


Dead Space x Battlefield 2042 crossover event looks fun, even if it isn't quite what Dead Space fans have been hoping for

Релиз Otherworld Three Kingdoms на смартфонах — новичкам дают 100 гача-круток

Глобальную версию Mega Man X DiVE закроют к концу июля

The internet is not a free-for-all—we shouldn't let big tech companies wish copyright out of existence



ТО-МÁ ворвалась в офис и устроила танцы в своем новом клипе на песню «Помада»

Пожар в центре Москвы локализован на площади 600 квадратных метров

В Подмосковье росгвардейцы провели тематическую встречу с детьми

«Зрителей будет ждать неслабый аттракцион»: стартовали съемки продолжения сериала «Бедные смеются, богатые плачут»




Пожар в центре Москвы локализован на площади 600 квадратных метров

Начались съемки комедии «Сокровища гномов» с Никитой Кологривым

Водитель Tesla погиб в ДТП на Кутузовском проспекте

В Москве арестовали военкома Тригилева по делу о взятке


«Дневник морфиниста» и «Вишневый сад»: куда сходить в Москве на выходных

Почему Индия ходит по натянутому канату между США и ...

Аутлеты Vnukovo и Novaya Riga презентовали новую концепцию

В тульский "Арсенал" перешли Минаев, Азявин, Липовой и Дмитриев


ПКР поздравляет чемпионку Паралимпийских игр по настольному теннису Р. Чебанику с Юбилеем

Более 100 спортсменов в Саратове принимают участие в Кубке России по настольному теннису памяти Паралимпийской чемпионки Наталии Мартяшевой

Рублёв впервые с 2021 года проиграл в первом круге турнира Большого шлема

30-я победа в сезоне: Медведев справился с Мюллером, а Карацев из-за травмы не доиграл матч с Хачановым на Уимблдоне


Аутлеты Vnukovo и Novaya Riga презентовали новую концепцию

МЖД: на станции Электрозаводская поврежден контактный провод, поезда не ходят

Административно-деловой центр появится на севере Москвы в рамках горпрограммы

«Дневник морфиниста» и «Вишневый сад»: куда сходить в Москве на выходных


Музыкальные новости

Портрет Джона Леннона экс-участника The Beatles оценили в £20 тысяч

Встречайте «Рекорд Оркестр» на «Квартирнике у Маргулиса» в ЦДКЖ

Филипп Киркоров, Баста, Тимати, Seville и другие гости открытия средиземноморского ресторана Zea

Детектив Финник на VK Fest



ТО-МÁ ворвалась в офис и устроила танцы в своем новом клипе на песню «Помада»

«Зрителей будет ждать неслабый аттракцион»: стартовали съемки продолжения сериала «Бедные смеются, богатые плачут»

Заместитель генерального директора ГПМ Радио по дистрибуции и технологиям отмечен наградой «Медиа-Менеджер России – 2024»

В Подмосковье росгвардейцы провели тематическую встречу с детьми


У Владимира Путина и Нарендры Моди нашлось много общего // Россия и Индия перезапускают двусторонние отношения

Совладелец «ТЕХНОНИКОЛЬ» Игорь Рыбаков запустил на Дальнем Востоке бизнес-клуб «Эквиум»

Йошкар-Ола готовит будущих чемпионов по фитнес-аэробике РФ

Вопросы стратегического развития водного хозяйства РФ обсудили в Росводресурсе


Два человека сгорели в «Газели» при аварии на МКАД

Два человека заживо сгорели в микроавтобусе при ДТП на МКАД

Источник 360.ru: Toyota и Tesla столкнулись в Москве, пострадали три человека

В Москве нашли двух ротвейлеров, которые несколько дней сидели в машине без воды


FT: Орбан после переговоров с Зеленским встретится с Путиным в Москве

Сийярто о реакции ЕС на визит Орбана в Москву: Венгрия - суверенная страна

У Владимира Путина и Нарендры Моди нашлось много общего // Россия и Индия перезапускают двусторонние отношения

Орбан заявил в Москве, что провел переговоры с Путиным, когда Европе нужен мир





Стоя или сидя: как поза при употреблении пищи влияет на пищеварение, рассказал гастроэнтеролог Садыков

Главный врач клиники микрохирургии глаза АйМед Элина Санторо: когда глаза разных цветов - норма и патология

Оливки или маслины: доктор Кутушов раскрыл их преимущества

Мэр Москвы вручил государственные награды врачам и медицинским сестрам


Орбан ответил на вопрос Life.ru о реакции Зеленского на предложение о мире

Путин намекнул: Капитуляцию придётся подписывать в Киеве, а не посредникам

Ушаков: Орбан не передавал Путину посланий от Зеленского

В Киеве заявили, что Зеленский оскорбил Карлсона, внезапно отказав ему в интервью


Команда Росгвардии победила на всероссийских соревнованиях общества «Динамо» по легкоатлетическому кроссу

Молодежное первенство. "Пари НН" и "Урал" разгромно уступают дома.

Иванникова Наталья прошла в полуфинал конкурса «Лидеры строительной отрасли»

Победитель Олимпиады-80 Николай Корольков умер в возрасте 77 лет


Лукашенко и Си Цзиньпин провели встречу в Астане

У Орла появился город-побратим - белорусский Гомель



Собянин: Путепровод от улицы Хачатуряна до Дубнинской будет достроен в этом году

Сергей Собянин утвердил проект нового участка Рублево-Архангельской линии метро

Сергей Собянин вручил награды московским врачам и медсестрам

Собянин рассказал о реализации программы реновации в Москве


Биолог Марьинский: богомолы станут частью фауны Москвы и Подмосковья

Москвичам предложили охлаждаться в жару в туманизаторах

Москвичам объяснили, как связаны смерчи и массовая застройка

В Подмосковье росгвардейцы провели тематическую встречу с детьми


Почему Индия ходит по натянутому канату между США и ...

Чествование ветеранов боевых действий прошло в Музее Победы

Административно-деловой центр появится на севере Москвы в рамках горпрограммы

«Все заливает»: на Москву обрушился ураган «Орхан»


Сергей Собянин утвердил проект нового участка Рублево-Архангельской линии метро

Терминал сбора данных (ТСД) промышленного класса SAOTRON RT42G

Жителей Поморья приглашают на «Семейный пикник»

Собянин: Утвержден проект участка метро от «Липовой рощи» до «Ильинской»


Героико-патриотическая выставка «И грянул бой, Полтавский бой!»

В Крыму заключили брак 74-летний жених и 86-летняя невеста

Михаил Ведерников поздравил владыку Тихона с днем рождения

Выставка-настроение «Семья, согретая любовью, всегда надежна и крепка»


«Все заливает»: на Москву обрушился ураган «Орхан»

Почему Индия ходит по натянутому канату между США и ...

Административно-деловой центр появится на севере Москвы в рамках горпрограммы

Фестиваль-путешествие «Достоевский» пройдет в Зарайске 20–21 июля












Спорт в России и мире

Новости спорта


Новости тенниса
Уимблдон

Уимблдон. 4 июля. Марреи сыграют пару последним запуском на Центральном корте, Зверев сыграет на Корте №1






В заповеднике коал людям запретили брать животных на руки

Перебои при подаче воды в ЖК «Новогорск-Парк» в Химках устранят в июле

«Расту в «парниковых» условиях»: девушка Лепса Киба рассказала об их отношениях

Подмосковные рапиристы завоевали 3 золотых медали на спартакиаде учащихся