Skip to content

Instantly share code, notes, and snippets.

import numpy as np
import tensorflow as tf
def unpickle(file):
import cPickle
fo = open(file, 'rb')
dict = cPickle.load(fo)
fo.close()
if 'data' in dict:
dict['data'] = dict['data'].reshape((-1, 3, 32, 32)).swapaxes(1, 3).swapaxes(1, 2).reshape(-1, 32*32*3) / 256.
import random
### Wikipedia sample Python implementation of the Mersenne-Twister.
### https://en.wikipedia.org/wiki/Mersenne_Twister
def _int32(x):
return int(0xFFFFFFFF & x)
def temper(y):
y = y ^ y >> 11
@LaurentMazare
LaurentMazare / fft.py
Created November 2, 2014 11:03
Naive FFT multiplication in python
import string
import random
import cmath
# Only works if len(cs) is a power of 2
def fft(cs, sign):
n = len(cs)
if n == 1: return [cs[0]]
cs1, cs2 = [], []
for i, c in enumerate(cs):
@LaurentMazare
LaurentMazare / fft.ml
Created November 1, 2014 18:11
Naive FFT multiplication
let pi = 4. *. atan 1.
module Complex = struct
type t = {
re : float;
im : float;
}
let re t = t.re
let im t = t.im
@LaurentMazare
LaurentMazare / tonelli_shanks.c
Created September 28, 2013 19:33
A simple implementation of the Tonelli-Shanks algorithm to compute a square root in Z/pZ where p is prime. It could probably be made quite faster by using a faster pow_mod function instead of the recursive one and also by trying to avoid some of the modulus calculations.
long pow_mod(long x, long n, long p) {
if (n == 0) return 1;
if (n & 1)
return (pow_mod(x, n-1, p) * x) % p;
x = pow_mod(x, n/2, p);
return (x * x) % p;
}
/* Takes as input an odd prime p and n < p and returns r
* such that r * r = n [mod p]. */
module V1 = struct (* runs in 2.36s *)
let rec pow ~mod_ x = function
| 0 -> 1
| n when n mod 2 = 0 ->
let x = pow ~mod_ x (n/2) in
(x * x) mod mod_
| n -> (pow ~mod_ x (n-1) * x) mod mod_
end
module V2 = struct (* runs in 2.02s *)
@LaurentMazare
LaurentMazare / pyth2.ml
Last active December 21, 2015 06:18
Uniquely generate integer triples (a, b, c) such that 2*a*a + b*b = c*c with a+b+c <= max_s.
let rec gcd x y = if y = 0 then x else gcd y (x mod y)
let fold_prim init f max_s =
let rec loop acc m n =
let m2 = m * m in
let n2 = n * n in
let mn = m * n in
if max_s < m2 then acc
else if max_s < 2*n2 + mn then
let n = int_of_float (float_of_int m /. 1.415) in
let factors max_n =
let open Bigarray in
let size = (max_n - 3) / 2 in
let f = Array1.create int c_layout (size + 1) in
for n = 0 to size do Array1.set f n 0 done;
for n = 0 to size do
if Array1.get f n = 0 then (
let nn = 2 * n + 3 in
Array1.set f n nn;
let m_times_n = ref (2 * n * n + 6 * n + 3) in