The post has been translated automatically. Original language: Russian
The use of random numbers in PC is not limited to games. They have great practical applications in the field of security, data encryption, noise generation for model training, and so on and so forth.
Now it doesn't cost a programmer anything to get such a number - it's enough to call the necessary function of the programming language. Random number generation is just a set of mathematical expressions, and if they are always performed with the same parameters or initial conditions, the result will always be the same. For example 2+3*2 it will always be 8. Therefore, such generators use a certain initial value on the basis of which the next one is calculated, which will also be random to a certain extent. But this random initial value needs to be taken from somewhere. The easiest way to get the initial conditions on modern hardware is to use the computer clock or the time counter from the moment the PC starts, although there are other options. For example, radio noise, thermal noise of some semiconductor materials, quantum generators (based on particle decay detectors) and other hardware generators that will be a little more random. Software tools are essentially pseudorandom number generators.
At the dawn of the computer industry, everything was different. Computers didn't have clocks, there were no operating systems storing information about the moment the PC started, there were no random processes, everything was subject to strict mathematics, and it was quite problematic to take relatively random initial conditions somewhere. I first encountered this problem in high school, when I was writing programs in assembler for the Z80 and i8080 processors, and later when writing the 2048 game for Apple 1. And I'm still trying to decide.
I will not write algorithms or descriptions of ready-made generators, there is a lot of information on this subject on the web, instead I want to suggest that the reader try to stretch his brain and solve an interesting problem (preferably without AI prompts or online materials) - write a function (algorithm) and get a pseudorandom number without using a PC clock or operating system capabilities.
Write your options in the comments. It will be interesting to discuss them.
Использование случайных чисел в ПК не ограничивается играми. У них большое практическое применение в области безопасности, шифрования данных, генерации шума для обучения моделей и прочее и прочее.
Сейчас программисту ничего не стоит получить такое число - достаточно вызвать нужную функцию языка программирования. Генерация случайного числа это просто набор математических выражений, и если их выполнять всегда с одними и теми же параметрами или начальными условиями, результат всегда будет один и тот же. Например 2+3*2 всегда будет 8. Поэтому такие генераторы используют некое начальное значение на базе которого рассчитывается следующее, которое тоже будет случайным до определённой степени. Но это случайное начальное значение нужно где то взять. Самый простой вариант получения начальных условий на современном железе - использовать часы компьютера или счётчик времени от момента запуска ПК, хотя есть и другие варианты. Например, шум радиоэфира, тепловой шум некоторых полупроводниковых материалов, квантовые генераторы (на базе детекторов распада частиц) и прочие аппаратные генераторы, которые будут немного случайнее. Программные же средства являются по своей сути генераторами псевдослучайных чисел.
На заре компьютерной индустрии всё было иначе. В компьютерах не было часов, не было операционных систем, хранящих информации о моменте запуска ПК, не было случайных процессов, всё подчинялось строгой математике, и было довольно проблематично где то взять относительно случайные начальные условия. С этой задачей я впервые столкнулся ещё в школе, когда писал на ассемблере программы под процессоры Z80 и i8080, а позже, и при написании игры 2048 для Apple 1. И я всё ещё продолжаю ещё решать.
Не буду писать алгоритмы или описания готовых генераторов, в сети очень много информации на этот счёт, вместо этого хочу предложить читателю попробовать размять мозги и решить интересную задачу (желательно без подсказок AI или материалов в сети) - написать функцию (алгоритм) и получить псевдослучайное число без использования часов ПК или возможностей операционной системы.
Пишите в комментариях Ваши варианты. Будет интересно их обсудить.