- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
- 10
- 11
- 12
- 13
- 14
- 15
- 16
Complex numbers:
>> Complex()({r: 2, i: 0} / {r: 1, i: 1} + {r: -3, i: 2}))
<- {r: -2, i: 1}
Automatic differentiation:
Let f(x) = x^3 - 5x:
>> var f = x => Dual()(x * x * x - {x:5, dx:0} * x);
Now map it over some values:
>> [-2,-1,0,1,2].map(a=>({x:a,dx:1})).map(f).map(a=>a.dx)
<- [ 7, -2, -5, -2, 7 ]
i.e. f'(x) = 3x^2 - 5.
Polynoomials:
>> Poly()([1,-2,3,-4]*[5,-6]).map((c,p)=>''+c+'x^'+p).join(' + ')
<- "5x^0 + -16x^1 + 27x^2 + -38x^3 + 24x^4"
В ЙажаСцрипт завезли перегрузку операторов.
https://gist.github.com/pyrocto/5a068100abd5ff6dfbe69a73bbc510d7
guest6 02.09.2021 11:26 # +1
3.14159265 02.09.2021 11:30 # +2
There are four evil kludges at play here. The first is one that various others have discovered: the arithmetic operators do coersion on their operands, and if the operand is an object (as opposed to a primitive), then its valueOf method gets invoked. So the question becomes, "What value should valueOf return?" The result of coersion has to be a number or a string, and multiplication only works with numbers, so we have to return a number.
People have tried packing data about the operand into JavaScript's IEEE 754 floats, but they only hold 64 bits. So if you have a Point(x, y) class, then you can represent it as the number x * 10**12 + y or some such, but the points have much more limited precision and you can only add and subtract them. This is almost useless for polynomials.
The second trick is to have the valueOf method store this in a table (line 123) and use the result of the expression to figure out what to do with the values in the table. Others have also discovered this before. This way we get to store all the information about the objects we're manipulating, but it's still not clear what number to return. This guy uses the number 3 to be able to do a single subtraction, a single division, multiple additions, or multiple multiplications.
CEHT9I6PbCKuu_nemyx 02.09.2021 16:46 # +1
CEHT9I6PbCKuu_nemyx 02.09.2021 16:54 # 0
3.14159265 02.09.2021 20:00 # +3
https://govnokod.ru/17323
Но автор пошёл гораздо дальше.
CEHT9I6PbCKuu_nemyx 02.09.2021 17:01 # 0
Интересно, но опасно. Во-первых, можно испортить данные при переполнении компонентов. Во-вторых, можно испортить данные из-за ошибок округления при умножении и делении, ведь это плавающий питух, который априори говно. Скакнёт порядок, и компоненты потеряют младшие биты.