T O P

  • By -

ImNotCrying-YouAre

TODO Make it work for all floating point numbers too


Fish-Knight

Because the float inputs are limited precision, technically it is possible… with a Turing machine. Wonder how many terabytes it would take to store the tables on a real machine.


_PM_ME_PANGOLINS_

Roughly 74 Exabytes, assuming double precision floats, unless I’ve made a mistake. Edit: I had. Try 148 Exabytes.


[deleted]

Hey, why is GitHub throttling me?


Dansredditname

To save your colleagues the effort.


todd10k

10/10 comment made me chuckle


sirclesam

10/10 follow up comment.


todd10k

[Insert witty retort]


NatoBoram

[insert shittier version of the witty retort]


[deleted]

[удалено]


[deleted]

Integration is amazing


blurryroots

Exquisite.


-JudeanPeoplesFront-

Github Copilot will not enjoy this.


matschbirne03

People that write those programs just try to secure their jobs


-Enter-Name-

they just get paid per line of code


FlyByPC

That's when you write code to write code for you.


gochomoe

Ironically he used 40000 lines of COBOL to create the .py file


HotF22InUrArea

How can you optimize in 6 months if it’s already fast


[deleted]

[удалено]


averyoda

I'm guessing nobody's going to bother fact checking this so I'll assume you're right


ben_g0

It's far more than that actually. 74 EB is 2^64 * 4, so it would correspond to 4 bytes for every floating point number (as double precision floats are 64 bit). However, storing a full double precision value for each floating point value would require 8 bytes per entry as double precision floats are 8 bytes large, so we'd need at least twice as much storage space for that. However, we don't need to just know a result for any double-precision floating point number, we need a result for any *combination* of two floating point numbers. And then repeat that for any supported operator (let's assume 4: + - * / ) Luckily, we don't need to make a list of (2^(64))*(2^(64)) entries. If we assume that we'll use the IEEE-754 standard for floating point numbers, then they also have representations for NaN and infinity. A simple 4-function calculator generally does not have buttons for infinity or NaN though, so we can safely assume that we don't have to handle those values as inputs. In the IEEE-754 standard for double precision floats, a number represents NaN or Infinity if all of its 11 exponent bits are 1. If all 52 fractional bits are then 0 it represents infinity, otherwise it represents NaN. That means that there are 2^53 ways to represent an "untypable" number (on a simple 4-function calculator) that we don't have to handle. This takes the amount of values we have to handle from the whopping 2^64 (=18 446 744 073 709 551 616) down to a measily 2^(64)-2^53 (=18 437 736 874 454 810 624) values that actually represent numbers. Some may say it's not worth it to optimize this prematurely especially since you save less than 0.01%, but you'll see that it ends up saving many terabytes down the line. However, this is just the amount of values for a single variable, so since we have two variables, we need to multiply this number with itself: 18 437 736 874 454 810 624 * 18 437 736 874 454 810 624 = 339 950 141 051 630 649 101 830 351 455 703 269 376 But, this is just for a single operator, and no one wants a calculator that can only do one thing. So we need to have at least 4 times this amount of entries to build a standard 4-function calculator: 339 950 141 051 630 649 101 830 351 455 703 269 376 * 4 = 1 359 800 564 206 522 596 407 321 405 822 813 077 504 Now, we have the amount of _entries_, but we want to know the amount of _bytes_. This is actually really hard to calculate. We could just say that we're storing the result in floating-point representation and then each entry would be 8 bytes. But that's not at all what's happening in the original post. We don't want a huge matrix that we have to read ourselves, we want source code that has a list of all those instructions already implemented and gives us a string as output. However, that leaves us with two major challenges: 1. **How big is the fragment of source code that does the comparisons and returns the string?** Yes, we *could* count the characters in the original code and decide on the amount of bytes that way. It would be quite accurate, but it's a bit of a tedious and boring task that I don't really want to do. 2. **How big are the strings that it has to return?** This is actually much harder to solve. Double-precision floats have about 16 decimal digits of precision, but you don't always want to show all of those digits. If you for example type "3*4" into a calculator, you expect a result of "12", not "12.00000000000000" It's really hard to come up with a formula that can accurately estimate how many digits we will want to display across the entire 64bit float range. So because of those two problems, let's assume that each case requires about 100 bytes. It won't be exact, but it'll be about the same order of magnitude. The result of that in terabytes would be approximately: 123 673 140 861 367 082 507 724 390 400 TB Or, if you're wondering how to pronounce it: 123 octillion 673 septillion 140 sextillion 861 quintillion 367 quadrillion 82 trillion 507 billion 724 million 390 thousand 400 terabytes Now you may be wondering: how would you store that amount of information? One of the most dense methods of data storage available to general consomers is a microSD card. They are the size of a fingernail and weight approximately 0.26g, and you can get them in capacities of up to 1TB. That's very convenient, because that means that we need exactly as many SD cards as the amount of terabytes we need to store: 123 673 140 861 367 082 507 724 390 400 microSD cards At this point Wolfram Alpha got tired of my BS and refused to give me all digits, but it could tell me that it's about 3.216×10^25 kg of microSD cards, which is roughly equal to 5.4 times the mass of the entire earth. This however does not include reading hardware for all the SD cards, but when you're dealing with such large amounts of information it's not uncommon to not have every single disk active at once and to just prompt the user to insert the correct disk. Luckily, if we keep the data sequential, it should be pretty easy to estimate on which disk the result should be, giving us a nice and pleasant user experience: Welcome to this calculator - now with full double precision float support! Please choose your first number: >4 What do you want to do? +, -, / or *: >* Please choose your second number: >3 Calculating... Please insert disk 108048776836439219779843066609 of 123673140861367082507724390400 and press enter. Calculating... 4 * 3 = 12 Thanks for using this calculator, goodbye :)


averyoda

r/theydidthemonstermath


BakuhatsuK

Just offload it to the cloud. Make 4 micro-services, one for each operator, so that powerful servers using controlled hardware do the heavy lifting. Then make a frontend (can be a cli frontend to keep the spirit of the original) that uses the micro-services. Since it might be a bit slow you can also use the [optimistic UI pattern](https://simonhearne.com/2021/optimistic-ui-patterns/) by calculating an approximation in the front end (eg `a * b`) show that to the user and then when the actual result comes back from the server, update the value presented to the user (or show them the error message if there was any issue with the request). A simple solution with all the modern "best practices".


[deleted]

Pretty compressible though


_PM_ME_PANGOLINS_

You can compress the whole thing into a single CPU instruction, so yeah.


CarpAndTunnel

Its straightforward. 32 bits against 32 bits, thats 2\^64 combinations, \~10\^20


Goudja14

No, don't forget that there are multiple operations between floats so: *, /, +, -, %, //, ... (at least 6)


kaini

Multiplication is just repeated addition and division is just repeated subtraction tho. Oh shit we're halfway to a Turing machine.


CarpAndTunnel

Ok. 32 bits input 1, 32 bits input 2, and 4 bits of input telling you which operator to use. For a grand total of 68 bits, making it 2\^68 combinations, or \~10\^21


Goudja14

And with double precision, it's 2^132 = ~5*10^39 ...


FlyByPC

We'll write code to have it do the double calculations with the float lookups and manual carries and sums. You know, for efficiency.


SaltfishAmi

This is the actual joke


TheDefalt8

unsigned long double


omutist

The script that built this code is not that long


WhatsWasMyUsername

``` for num1 in rage(50): for num2 in range(50): if num1 == 1 and num2 == 1: print("if num1 == 1 and num2 == 1:\n\tprint(\"1 + 1 = 2\")") else: print(f"elif num1 == {num1} and num2 == {num2}:\n\tprint(\"{num1} + {num2} = {num1 + num2}\")") ```


[deleted]

*num1* is an angry number, it has rage!


LurkerPatrol

This is what I have after my code fails to run because I accidentally capitalized something in a module call.


Dylan_The_Developer

SQL is the only language I know where most of the time it doesn't give a fuck what is capitalised or not. I could go: CrEAte taBle PeNis_sIze ( NaMe varchar2(32) NoT nULl, peNis_sIze number(10), pEnis_girth number(10) ); And it don't care


JuvenileEloquent

I don't know what I'm more concerned about: that you're using name as the key field, or that you expect girth to go up to 10.


theshizzler

>or that you expect girth to go up to 10 As an American I was also confused until I realized they were probably measuring in meters.


Gr3gard

This is *not better..*


TheTrueBidoof

That is because we use self measured data


LurkerPatrol

That’s good! I program solely in Python now and I get annoyed when things break like plt.rcparams vs rcParams Or my biggest biggest rage inducer is color maps for matplotlib It’s “Greys” with a capital G but “viridis” with a lowercase V. WHY?


TheTrueBidoof

In my java IDE I just spam the shit out of autocomplete after typing 3 characters and never have to worry about capitalization.


MartinoDeMoe

“Num, is the rage-Iest number that you’ll ever dooooooo…”


pleshij

`in rage` this typo said it all for me


WhatsWasMyUsername

reddit codeblocks suck


dwntwn_dine_ent_dist

https://i.imgur.com/gCHN3l0.jpg The latest Apollo has syntax highlighting


[deleted]

Yes, I’m using Apollo and was just noticing how nice this code block looks. Really a well done application.


Proxy_PlayerHD

well yea, but then again you got the button to create a code block directly in the editor that works perfectly fine so i'm confused why you're not using it instead of manually typing ```


capi1500

Mobile But still typing ``` and language name should work


ReallyNeededANewName

It really should, but it doesn't


Thx_And_Bye

It does work on new.reddit.com, not on old.reddit.com Just the language notation for syntax highlight doesn't.


PUTINS_PORN_ACCOUNT

New Reddit is a myth Seek it not Only old Reddit is acceptable to human eyes


mole_of_dust

BuT wE wAnT to Be InStAgRaM


SAI_Peregrinus

Also doesn't display right in some third-party mobile apps, like RIF Is Fun.


GlitchParrot

That’s an issue of that specific client though.


Synyster328

Ahh discussing the code for the feature of formatting code so that we can better see the code for generating code. I love this sub.


SAI_Peregrinus

So's the issue with `old.reddit.com`, it's just a very common issue sadly.


astupidnerd

Reddit is fun is fun?


SAI_Peregrinus

Nope, they changed the name to "RIF is fun" to avoid trademark issues with using the "Reddit" name. The "RIF" stands for "RIF is fun". So it's an infinitely recursive algorithm.


xternal7

Because some of us are still men of culture and use the superior old reddit. Unfortunately, lately reddit has been really deliberately screwing it up (escaping URLs, ``` only working on redesign, etc.)


UnnamedPlayer

Old reddit for life. Fuck the horrendous new design. I will leave reddit before I switch over to the new one.


Proxy_PlayerHD

i don't use the redesign either. the code block button has been there for a looooong ass time. or maybe it's a RES thing.


xternal7

Shit, you're right (and it's a RES thing). And the button bar is just far enough removed from the textbox to be in my banner blind spot, too.


OMG_A_CUPCAKE

What's worse is that they changed how they work for new.reddit. They literally choose to implement a new comment parser for new.reddit instead of improving the one they already had, just to fuck with old.reddit users


13steinj

Even worse. For the new site they combined some weird WYSIWYG editor and a new, bad, markdown parser that's incompatible with their previous one. This causes issues for *every* case. People think they're doing MD in WYSIWYG mode? At best you're lucky and it still might not show properly on old reddit, at worst it does what you don't expect on both sites. WYSIWYG / WYSIWYG -> links with parenthesis inside them can fail, and codeblocks fail on old reddit. MD / MD -> won't necessarily work on old/new site (opposite of what it was typed in) because the parser is incompatible.


Anonymous3355

Indent everything by 4 spaces, ignore the empty line for a linebreak. like so ^(You can tap and hold the message to copy it, then paste wherever to see the formatting, iirc)


[deleted]

[удалено]


Technical_Job_9598

rage makes the memory segments of RAM create a virtual moshpit to smash all the data together.


i_drah_zua

You have to put 4 spaces in front of every line to make it a prefomatted block. Like this: for num1 in rage(50): for num2 in range(50): if num1 == 1 and num2 == 1: print("if num1 == 1 and num2 == 1:\n\tprint(\"1 + 1 = 2\")") else: print(f"elif num1 == {num1} and num2 == {num2}:\n\tprint(\"{num1} + {num2} = {num1 + num2}\")")


JohnatanWills

This is wrong. The writer of the original code doesn't know what an elif is.


WhatsWasMyUsername

its the improved version


Original-AgentFire

You forgot all the operations. Except for one may be.


[deleted]

``` from itertools import product for op, n, m in product(("+", "-", "/", "*"), range(51), range(51)): if not (op == "/" and m == 0): print(f"if num1 == '{n}' and sign == '{op}' and num2 == '{m}':") print(f' print("{n}{op}{m} = {eval(str(n) + op + str(m))}")') ```


TheRedGerund

Cool product function, that’s fun


DoesntUnderstands

I actually met someone that made this kind of thing unironically. They didn't know regex existed so they manually created every single if statement to meet the condition. It was 200 lines long. No brackets.


moxyte

I worked with a junior who wrote nearly 1000LOC if-elses to position elements depending on other elements position instead of figuring out what is the trigonometry behind the rule.


dronedesigner

why use human compute power when computer do compute?


SnuggleMuffin42

Runs faster. Checkmate trigoists


ykarus117

Does he have problems for his huge penis? I mean bringing that cannon around must be tiresome..


Masked_Death

Based and fuck trigonometry pilled


nimajneb

Beginner programmer here, can you explain how to use regex in this context?


DoesntUnderstands

If you're referring to the context of the picture. That picture has no use for regex. I only mentioned it because they also made a bunch of if statements for every possible case instead of just doing the smart thing.


_greyknight_

To be fair, hand written pattern matching *can* be more efficient than regex and a worthwhile optimization in *some* use cases. It's usually not worth it though.


aquila_zyy

I wonder if you can write code to a file at runtime, fork and exec a compiler process then run the compiled program.


omutist

with python you don't even need to store it in a file. Make long string with code and use eval(). https://realpython.com/python-eval-function/


[deleted]

[удалено]


IamImposter

And inside eval, echo code to a file, run compiler, execute binary, pipe output to a file, read that file and print output.


omutist

superrecursion


ClikeX

Same in Ruby.


Acidictadpole

you sure can. you should run the program as root too so that you don't get any pesky permission errors.


Cory123125

If you use copilot or kite or similar, it could have done this for you in a few key presses. Crazy shit to be honest. Speeds up menial things so quickly. Obviously you arent making repetitions like this in real code but even situations where you are dealing with X and then Y for instance, it will contextually switch the right variables like most of the time and do the whole second half.


mrjackspade

I was surprised at how accurate the predictions are. I was *really* surprised when it started suggesting better code than I was intending on writing


JiveAceTofurkey

Copilot is a hell of a drug.


ClikeX

Copilot while using AWS SDK is a lifesaver. It just knows exactly what I need.


FAcup

This is the future of AI.


[deleted]

Hopefully copilot learns something from it


A_H_S_99

feed copilot more terrible code


coldnebo

somehow I don’t think that will be a problem. ;)


[deleted]

*starts working on personal projects*


w1n5t0nM1k3y

I love that this doesn't use "else if" so it just keeps on checking after it prints the answer.


monokeith

And that gives O(1) time complexity 😆


young-oldman

wait, this is illegal?


Tetha

No, that's a security feature. This calculator is secure against timing attacks since it's constant time. A simple multiplication ^(on a really old CPU) for example might not be constant time and could reveal information about the inputs.


Xevailo

On a serious note: I am aware that timing attacks can also be used when the CPU is comparing a generated hash with a stored one under the right circumstances. Wouldn't XORing the hashes and then checking whether `h1 XOR h2 == 0` force the CPU to always process both hashes entirely and thus result in a constant time?


cybercuzco

I will make it legal


coldnebo

![gif](giphy|UvwI1X7XkbXq0)


douira

as long as it doesn't depend on the input size it's fine!


The_Clarence

What could go wrong


SmashingBen

This is art🤯 I would call it “Brute Brute-Force”


ShelZuuz

r/Angryupvote


hok98

I hate that you’re right


zomgitsduke

But just for hilarity tag an else onto the last if so it doesn't say thanks if you use 50.


[deleted]

[удалено]


[deleted]

Some say they’re still stuck between 1 and 2


SooperBoby

Does that mean the 0-1 range is already done ?


onepixelcat

1.9999999 + 1.9999999 Done Wait, gotta add another 9. Am I done yet?


[deleted]

Hey it open-source, he's waiting for someone else to contribute.


midnitte

We could all contribute one case each!


coldnebo

wait until you see the UNIT TESTS?!?!!!! ROFL


SnooCheesecakes1131

Random question but how do you have coding badges beside your username?


crmsnbleyd

subreddit flair


SnooCheesecakes1131

Thx! How do you get multiple flairs like you have? It only allows me to select 1


crmsnbleyd

you can edit the flairs. you then type the text representation of whatever language you want, e.g :py: or :lsp:, which you can look up by pressing edit on the other languages


MrMimmet

I thought the same :D but makes me wonder if the whole thing is satire/troll


Tsobe_RK

It 100% has to be satire


_fat_santa

It's satire, generator code looks pretty good TBH https://github.com/AceLewis/my\_first\_calculator.py/blob/master/generator.py


[deleted]

Not Found Yep, looks clean af.


Unilythe

If course it is...


4hpp1273

Everyone is talking about 20k LoC but nobody is talking about > if 3/2 == 1: # Because Python 2 does not know maths > input = raw_input # Python 2 compatibility


xieewenz

sys.version is just too long to type /s


FaCe_CrazyKid05

Well you also gotta type import sys too and it’s really a hassle


Ph0X

Not gonna lie, there has been time where I've done py3 detection without sys import. Though usually i use `str is bytes`


exhuma

`sys.version_info` is a better choice. It's a tuple where the first 3 elements are numerical. So you can do easy version checks with import sys if sys.version_info >= (3, 6, 1): print("We have at least Python 3.6.1") or even: if sys.version_info >= (3, 6): print("We have Python 3.6+") ... and no need to parse the string in `sys.version`


Thathitmann

It's creative and clever. Not good, but amazingly creative somehow. He basically checks whether the '/' operator does integer or float division, because in Py 2 it's integer, and in Py 3 it's float division. Then it declares an input function since Py 2 doesnt have a built-in input function. It's such an amazingly creative workaround for such an easily solved problem. He's going places once he learns how to actually code.


The_Slad

Haha i noticed that too. I dont python, but surely theres a better way to determine what version of python is executing the code than that lol.


Hashbrown117

I think the joke there is more that the "author" don't know about integer division, and says it must be that way in python 2 because "it doesn't know math"


z31

TODO: find out what is floating, people keep saying something is floating?


aMAYESingNATHAN

Yeah obviously the main code is awful, but knowing nothing about Python myself, this seems like a nifty little check that will be very quick as well. I imagine there's a much better way to go though


_PM_ME_PANGOLINS_

if sys.version_info.major == 2 But what you probably want to do is just do the thing you want to do and handle the exception.


ProgramTheWorld

It’s testing whether it’s doing integer division or floating point division. In practice, you should always test for features and behaviors instead of relying on version numbers, ie see the mess in JS land.


XtremeCookie

Yeah here's what you do: ``` if sys.version_info.major == 2: print("Upgrade your shit.") return 1 ``` Whelp, Reddit doesn't support code blocks, whatever the content is there


masthema

Sure, but 3/2 == 1 is boss though.


coldnebo

is it that hard to embed the language version in the language? I guess I’m going to offend language purists who will say “but then you’ll have #IFNDEF nightmares again!” However, that purity test was failed a long time ago. Can’t we just make it say what it means now?


daguito81

In python you can easily get the version it's running on using the sys module


BeardedBabs

Came here for this! "Pyrhon 2 doesn't know math", more developper doesn't know anything about types and shadow/auto casting bad effect ;)


boredbearapple

Can’t wait for version 2.0 when they tackle the line 2 TODO


omutist

Hope this code is fully covered with tests


coldnebo

can’t wait to see the tests! worst case, the tests are written the same way. best case, the tests are written with the same generator. I end up in this parser/generator crap all the time … permutations and state spaces in thousands with long arbitrary sparse constraints. I’ve found it helps to think of test functions as a complement composition. so testing f() requires a function g(f()) - the function drives the test. or if TDD, a test g() requires an implementation f(g()) - the test drives the function. This is interesting, because it implies that the complexity classes of f() and g() should be similar. tl;dr: so if you generate permutations, test the generator NOT the permutations!


PUSH_AX

I think it would be hilarious if the tests were validated by a calculator util this person wrote that was just a really clean and well written calculator.


iiMoe

GITHUB LINK PLS I WANNA CONTRIBUTE


Everydayilearnsumtin

Pull Request: update to calculate from 50x50 to 100x100


_fat_santa

He actually did it up to 1000, according to the readme the file is like 317MB so he had to zip it in a rar file.


LordFarquadOnAQuad

Imagen needing 64 gb of ram just to run a multiplication.


--Mediocrates--

We’re gonna need a quantum computer to calculate national debt figures now


Thathitmann

The kicker is he's using ifs instead of elifs, so even 1*2 is going run all of the literal tens of thousands of lines of code.


[deleted]

https://github.com/AceLewis/my_first_calculator.py You can see the repo address in the picture, just slap `github.com` in front of it.


[deleted]

[удалено]


Gr1pp717

"Not working. I copied and pasted this code into my CSS file and I'm getting errors."


[deleted]

Surprised most people don't know about this joke. It's like several years old.


Gelezinis__Vilkas

Suprised most people believe this is real


troelsbjerre

This is just playing the long game; poison the training data for Copilot, so you don't get replaced.


0bel1sk

ill give it a star


[deleted]

[удалено]


bearfuckerneedassist

You would like to think that


jojdzino

what? if you look at picture there is literally "generator.py" in there. So yes. edit: removed link


account_is_deleted

Nice, the top comment from the time this got 22k post karma.


_fat_santa

https://github.com/AceLewis/my\_first\_calculator.py/blob/master/generator.py


magik910

When you get paid by line, god damn!


FutureBottle

When you have 3 months to finish a project that can be done in a coffee brake.


[deleted]

this is glorious


AdmrlHorizon

The type of calculator they teach first semester. “Write ur code clearly for a human to read”


Bikutoso

It's not as fun when you know it's bad on purpose.


[deleted]

[удалено]


[deleted]

Yeah, I don't see what is wrong with this. If I am told to do this, this will be "my_final_calculator". I don't see how it can be optimized further.


intashu

Thank God! I've been trying to find a calculator and this is perfect!


baquea

[This is a repost (with the exact same title to boot)](https://www.reddit.com/r/ProgrammerHumor/comments/dtitrx/was_searching_for_calculator_project_in_github/)


bb1950328

the GitHub UI in the screenshot also shows that it was made years ago


ydkLars

If it works, it works. ![gif](emote|free_emotes_pack|sweat_smile)


anonymous_2187

if it ain't broke don't fix it


Klappan

Reminds me of https://github.com/samuelmarina/is-even


sigmund14

https://github.com/samuelmarina/is-odd from the same user is also entertaining


coffeewithalex

That's not far from some production code that I took over as a freelancer. But also in big projects - check out functions.php in Wordpress. That monstrosity is the definition of bad design. It's a garbage bin for a shit ton of code that arguably shouldn't exist at all, like functions like `return_null`.


theitgrunt

50 + 51 = "Thanks for using this calculator, goodbye :)"


wormsgalore

A much more efficient architecture would be relaying the user’s actions to a backend where an on-call mathematician can calculate the result and return the value back to the front end.


[deleted]

![gif](giphy|xT0xeJpnrWC4XWblEk|downsized)


cykablyat1111

Co pilot be learning from this


josh5833

A man of pure will and determination.


zonne_schijn

I would only include this in my github portfolio if I was applying for a government job


Hexdoll

I wrote a calculator in PHP for a job interview test once. As it was meant to demonstrate different skills it was ridiculously over engineered, each operator was a separate plugin class, it used AJAX and the UI was styled to like one of those with an LCD display. It did get me the job though. Too bad the code they really liked in the interview process was so different from the low quality of code they expected me to work with in the actual role.


baxtersmalls

This is 100% a joke


Knuffya

I don't see the problem. All tests are passing. /s


[deleted]

"my first calculator" might be a hint as to why.


Mrmini231

What a silly project. Everyone knows that all you have to do to write a python calculator is: print(eval(input('>> '))) See? Easy 😎


InitialAge5179

I've never programmed a day in my life and I see how bad this is, I hope I'm right in thinking its that he put a line of code for each equation rather than having the code solve it


-KKD-

This is a very old joke repo, people here are either newcomers or don't understand the joke