Python math.h() Examples

The following are code examples for showing how to use math.h(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: SwiftKitten   Author: johncsnyder   File: test_zdistutils.py    MIT License 6 votes vote down vote up
def test_extension_object(self):
        ffi = FFI()
        ffi.cdef("double sin(double x);")
        csrc = '/*7%s*/' % self + '''
    #include <math.h>
    #ifndef TEST_EXTENSION_OBJECT
    # error "define_macros missing"
    #endif
    '''
        lib = ffi.verify(csrc, define_macros=[('TEST_EXTENSION_OBJECT', '1')],
                         force_generic_engine=self.generic,
                         libraries=[self.lib_m])
        assert lib.sin(12.3) == math.sin(12.3)
        v = ffi.verifier
        ext = v.get_extension()
        assert 'distutils.extension.Extension' in str(ext.__class__) or \
               'setuptools.extension.Extension' in str(ext.__class__)
        assert ext.sources == [maybe_relative_path(v.sourcefilename)]
        assert ext.name == v.get_module_name()
        assert ext.define_macros == [('TEST_EXTENSION_OBJECT', '1')] 
Example 2
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    MIT License 6 votes vote down vote up
def test_opaque_integer_as_function_result():
    #import platform
    #if platform.machine().startswith('sparc'):
    #    py.test.skip('Breaks horribly on sparc (SIGILL + corrupted stack)')
    #elif platform.machine() == 'mips64' and sys.maxsize > 2**32:
    #    py.test.skip('Segfaults on mips64el')
    # XXX bad abuse of "struct { ...; }".  It only works a bit by chance
    # anyway.  XXX think about something better :-(
    ffi = FFI()
    ffi.cdef("""
        typedef struct { ...; } myhandle_t;
        myhandle_t foo(void);
    """)
    lib = ffi.verify("""
        typedef short myhandle_t;
        myhandle_t foo(void) { return 42; }
    """)
    h = lib.foo()
    assert ffi.sizeof(h) == ffi.sizeof("short") 
Example 3
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    MIT License 6 votes vote down vote up
def test_take_and_return_partial_structs():
    ffi = FFI()
    ffi.cdef("""
        typedef struct { int x; ...; } foo_t;
        foo_t foo(foo_t, foo_t);
    """)
    lib = ffi.verify("""
        typedef struct { int y, x; } foo_t;
        foo_t foo(foo_t a, foo_t b) {
            foo_t r = { 100, a.x * 5 + b.x * 7 };
            return r;
        }
    """)
    args = ffi.new("foo_t[3]")
    args[0].x = 1000
    args[2].x = -498
    h = lib.foo(args[0], args[2])
    assert ffi.sizeof(h) == 2 * ffi.sizeof("int")
    assert h.x == 1000 * 5 - 498 * 7 
Example 4
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    MIT License 6 votes vote down vote up
def test_FILE_stored_explicitly():
    ffi = FFI()
    ffi.cdef("int myprintf11(const char *, int); FILE *myfile;")
    lib = ffi.verify("""
        #include <stdio.h>
        FILE *myfile;
        int myprintf11(const char *out, int value) {
            return fprintf(myfile, out, value);
        }
    """)
    import os
    fdr, fdw = os.pipe()
    fw1 = os.fdopen(fdw, 'wb', 256)
    lib.myfile = ffi.cast("FILE *", fw1)
    #
    fw1.write(b"X")
    r = lib.myprintf11(b"hello, %d!\n", ffi.cast("int", 42))
    fw1.close()
    assert r == len("hello, 42!\n")
    #
    result = os.read(fdr, 256)
    os.close(fdr)
    # the 'X' might remain in the user-level buffer of 'fw1' and
    # end up showing up after the 'hello, 42!\n'
    assert result == b"Xhello, 42!\n" or result == b"hello, 42!\nX" 
Example 5
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    MIT License 6 votes vote down vote up
def test_ptr_to_opaque():
    ffi = FFI()
    ffi.cdef("typedef ... foo_t; int f1(foo_t*); foo_t *f2(int);")
    lib = ffi.verify("""
        #include <stdlib.h>
        typedef struct { int x; } foo_t;
        int f1(foo_t* p) {
            int x = p->x;
            free(p);
            return x;
        }
        foo_t *f2(int x) {
            foo_t *p = malloc(sizeof(foo_t));
            p->x = x;
            return p;
        }
    """)
    p = lib.f2(42)
    x = lib.f1(p)
    assert x == 42 
Example 6
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    MIT License 6 votes vote down vote up
def test_implicit_unicode_on_windows():
    if sys.platform != 'win32':
        py.test.skip("win32-only test")
    ffi = FFI()
    e = py.test.raises(FFIError, ffi.cdef, "int foo(LPTSTR);")
    assert str(e.value) == ("The Windows type 'LPTSTR' is only available after"
                            " you call ffi.set_unicode()")
    for with_unicode in [True, False]:
        ffi = FFI()
        ffi.set_unicode(with_unicode)
        ffi.cdef("""
            DWORD GetModuleFileName(HMODULE hModule, LPTSTR lpFilename,
                                    DWORD nSize);
        """)
        lib = ffi.verify("""
            #include <windows.h>
        """, libraries=['Kernel32'])
        outbuf = ffi.new("TCHAR[]", 200)
        n = lib.GetModuleFileName(ffi.NULL, outbuf, 500)
        assert 0 < n < 500
        for i in range(n):
            #print repr(outbuf[i])
            assert ord(outbuf[i]) != 0
        assert ord(outbuf[n]) == 0
        assert ord(outbuf[0]) < 128     # should be a letter, or '\' 
Example 7
Project: SwiftKitten   Author: johncsnyder   File: test_verify1.py    MIT License 6 votes vote down vote up
def test_opaque_integer_as_function_result():
    #import platform
    #if platform.machine().startswith('sparc'):
    #    py.test.skip('Breaks horribly on sparc (SIGILL + corrupted stack)')
    #elif platform.machine() == 'mips64' and sys.maxsize > 2**32:
    #    py.test.skip('Segfaults on mips64el')
    # XXX bad abuse of "struct { ...; }".  It only works a bit by chance
    # anyway.  XXX think about something better :-(
    ffi = FFI()
    ffi.cdef("""
        typedef struct { ...; } myhandle_t;
        myhandle_t foo(void);
    """)
    lib = ffi.verify("""
        typedef short myhandle_t;
        myhandle_t foo(void) { return 42; }
    """)
    h = lib.foo()
    assert ffi.sizeof(h) == ffi.sizeof("short") 
Example 8
Project: SwiftKitten   Author: johncsnyder   File: test_verify1.py    MIT License 6 votes vote down vote up
def test_FILE_stored_explicitly():
    ffi = FFI()
    ffi.cdef("int myprintf11(const char *, int); FILE *myfile;")
    lib = ffi.verify("""
        #include <stdio.h>
        FILE *myfile;
        int myprintf11(const char *out, int value) {
            return fprintf(myfile, out, value);
        }
    """)
    import os
    fdr, fdw = os.pipe()
    fw1 = os.fdopen(fdw, 'wb', 256)
    lib.myfile = ffi.cast("FILE *", fw1)
    #
    fw1.write(b"X")
    r = lib.myprintf11(b"hello, %d!\n", ffi.cast("int", 42))
    fw1.close()
    assert r == len("hello, 42!\n")
    #
    result = os.read(fdr, 256)
    os.close(fdr)
    # the 'X' might remain in the user-level buffer of 'fw1' and
    # end up showing up after the 'hello, 42!\n'
    assert result == b"Xhello, 42!\n" or result == b"hello, 42!\nX" 
Example 9
Project: SwiftKitten   Author: johncsnyder   File: test_verify1.py    MIT License 6 votes vote down vote up
def test_errno_working_even_with_pypys_jit():
    ffi = FFI()
    ffi.cdef("int f(int);")
    lib = ffi.verify("""
        #include <errno.h>
        int f(int x) { return (errno = errno + x); }
    """)
    @_run_in_multiple_threads
    def test1():
        ffi.errno = 0
        for i in range(10000):
            e = lib.f(1)
            assert e == i + 1
            assert ffi.errno == e
        for i in range(10000):
            ffi.errno = i
            e = lib.f(42)
            assert e == i + 42 
Example 10
Project: SwiftKitten   Author: johncsnyder   File: test_recompiler.py    MIT License 6 votes vote down vote up
def test_unicode_libraries():
    try:
        unicode
    except NameError:
        py.test.skip("for python 2.x")
    #
    import math
    lib_m = "m"
    if sys.platform == 'win32':
        #there is a small chance this fails on Mingw via environ $CC
        import distutils.ccompiler
        if distutils.ccompiler.get_default_compiler() == 'msvc':
            lib_m = 'msvcrt'
    ffi = FFI()
    ffi.cdef(unicode("float sin(double); double cos(double);"))
    lib = verify(ffi, 'test_math_sin_unicode', unicode('#include <math.h>'),
                 libraries=[unicode(lib_m)])
    assert lib.cos(1.43) == math.cos(1.43) 
Example 11
Project: D-VAE   Author: muhanzhang   File: basic.py    MIT License 5 votes vote down vote up
def c_headers(self, c_compiler):
        l = ['<math.h>']
        # These includes are needed by Scalar and TensorType,
        # we declare them here and they will be re-used by TensorType
        l.append('<numpy/arrayobject.h>')
        l.append('<numpy/arrayscalars.h>')
        if config.lib.amdlibm and c_compiler.supports_amdlibm:
            l += ['<amdlibm.h>']
        return l 
Example 12
Project: SwiftKitten   Author: johncsnyder   File: test_zdistutils.py    MIT License 5 votes vote down vote up
def test_write_source(self):
        ffi = FFI()
        ffi.cdef("double sin(double x);")
        csrc = '/*hi there %s!*/\n#include <math.h>\n' % self
        v = Verifier(ffi, csrc, force_generic_engine=self.generic,
                     libraries=[self.lib_m])
        v.write_source()
        with open(v.sourcefilename, 'r') as f:
            data = f.read()
        assert csrc in data 
Example 13
Project: SwiftKitten   Author: johncsnyder   File: test_zdistutils.py    MIT License 5 votes vote down vote up
def test_write_source_explicit_filename(self):
        ffi = FFI()
        ffi.cdef("double sin(double x);")
        csrc = '/*hi there %s!*/\n#include <math.h>\n' % self
        v = Verifier(ffi, csrc, force_generic_engine=self.generic,
                     libraries=[self.lib_m])
        v.sourcefilename = filename = str(udir.join('write_source.c'))
        v.write_source()
        assert filename == v.sourcefilename
        with open(filename, 'r') as f:
            data = f.read()
        assert csrc in data 
Example 14
Project: SwiftKitten   Author: johncsnyder   File: test_zdistutils.py    MIT License 5 votes vote down vote up
def test_write_source_to_file_obj(self):
        ffi = FFI()
        ffi.cdef("double sin(double x);")
        csrc = '/*hi there %s!*/\n#include <math.h>\n' % self
        v = Verifier(ffi, csrc, force_generic_engine=self.generic,
                     libraries=[self.lib_m])
        try:
            from StringIO import StringIO
        except ImportError:
            from io import StringIO
        f = StringIO()
        v.write_source(file=f)
        assert csrc in f.getvalue() 
Example 15
Project: SwiftKitten   Author: johncsnyder   File: test_zdistutils.py    MIT License 5 votes vote down vote up
def test_compile_module(self):
        ffi = FFI()
        ffi.cdef("double sin(double x);")
        csrc = '/*hi there %s!*/\n#include <math.h>\n' % self
        v = Verifier(ffi, csrc, force_generic_engine=self.generic,
                     libraries=[self.lib_m])
        v.compile_module()
        assert v.get_module_name().startswith('_cffi_')
        if v.generates_python_module():
            mod = imp.load_dynamic(v.get_module_name(), v.modulefilename)
            assert hasattr(mod, '_cffi_setup') 
Example 16
Project: SwiftKitten   Author: johncsnyder   File: test_zdistutils.py    MIT License 5 votes vote down vote up
def test_compile_module_explicit_filename(self):
        ffi = FFI()
        ffi.cdef("double sin(double x);")
        csrc = '/*hi there %s!2*/\n#include <math.h>\n' % self
        v = Verifier(ffi, csrc, force_generic_engine=self.generic,
                     libraries=[self.lib_m])
        basename = self.__class__.__name__ + 'test_compile_module'
        v.modulefilename = filename = str(udir.join(basename + '.so'))
        v.compile_module()
        assert filename == v.modulefilename
        assert v.get_module_name() == basename
        if v.generates_python_module():
            mod = imp.load_dynamic(v.get_module_name(), v.modulefilename)
            assert hasattr(mod, '_cffi_setup') 
Example 17
Project: SwiftKitten   Author: johncsnyder   File: test_zdistutils.py    MIT License 5 votes vote down vote up
def test_load_library(self):
        ffi = FFI()
        ffi.cdef("double sin(double x);")
        csrc = '/*hi there %s!3*/\n#include <math.h>\n' % self
        v = Verifier(ffi, csrc, force_generic_engine=self.generic,
                     libraries=[self.lib_m])
        library = v.load_library()
        assert library.sin(12.3) == math.sin(12.3) 
Example 18
Project: SwiftKitten   Author: johncsnyder   File: test_zdistutils.py    MIT License 5 votes vote down vote up
def test_verifier_args(self):
        ffi = FFI()
        ffi.cdef("double sin(double x);")
        csrc = '/*hi there %s!4*/#include "test_verifier_args.h"\n' % self
        udir.join('test_verifier_args.h').write('#include <math.h>\n')
        v = Verifier(ffi, csrc, include_dirs=[str(udir)],
                     force_generic_engine=self.generic,
                     libraries=[self.lib_m])
        library = v.load_library()
        assert library.sin(12.3) == math.sin(12.3) 
Example 19
Project: SwiftKitten   Author: johncsnyder   File: test_zdistutils.py    MIT License 5 votes vote down vote up
def test_verifier_object_from_ffi(self):
        ffi = FFI()
        ffi.cdef("double sin(double x);")
        csrc = "/*6%s*/\n#include <math.h>" % self
        lib = ffi.verify(csrc, force_generic_engine=self.generic,
                         libraries=[self.lib_m])
        assert lib.sin(12.3) == math.sin(12.3)
        assert isinstance(ffi.verifier, Verifier)
        with open(ffi.verifier.sourcefilename, 'r') as f:
            data = f.read()
        assert csrc in data 
Example 20
Project: SwiftKitten   Author: johncsnyder   File: test_zdistutils.py    MIT License 5 votes vote down vote up
def test_extension_forces_write_source(self):
        ffi = FFI()
        ffi.cdef("double sin(double x);")
        csrc = '/*hi there9!%s*/\n#include <math.h>\n' % self
        v = Verifier(ffi, csrc, force_generic_engine=self.generic,
                     libraries=[self.lib_m])
        assert not os.path.exists(v.sourcefilename)
        v.get_extension()
        assert os.path.exists(v.sourcefilename) 
Example 21
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    MIT License 5 votes vote down vote up
def test_simple_case():
    ffi = FFI()
    ffi.cdef("double sin(double x);")
    lib = ffi.verify('#include <math.h>', libraries=lib_m)
    assert lib.sin(1.23) == math.sin(1.23) 
Example 22
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    MIT License 5 votes vote down vote up
def test_Wconversion_floating():
    lib = _Wconversion("float sin(double);",
                       "#include <math.h>", libraries=lib_m)
    res = lib.sin(1.23)
    assert res != math.sin(1.23)     # not exact, because of double->float
    assert abs(res - math.sin(1.23)) < 1E-5 
Example 23
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    MIT License 5 votes vote down vote up
def test_Wconversion_float2int():
    _Wconversion("int sinf(float);",
                 "#include <math.h>", libraries=lib_m) 
Example 24
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    MIT License 5 votes vote down vote up
def test_Wconversion_double2int():
    _Wconversion("int sin(double);",
                 "#include <math.h>", libraries=lib_m) 
Example 25
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    MIT License 5 votes vote down vote up
def test_rounding_1():
    ffi = FFI()
    ffi.cdef("double sinf(float x);")
    lib = ffi.verify('#include <math.h>', libraries=lib_m)
    res = lib.sinf(1.23)
    assert res != math.sin(1.23)     # not exact, because of double->float
    assert abs(res - math.sin(1.23)) < 1E-5 
Example 26
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    MIT License 5 votes vote down vote up
def test_strlen_exact():
    ffi = FFI()
    ffi.cdef("size_t strlen(const char *s);")
    lib = ffi.verify("#include <string.h>")
    assert lib.strlen(b"hi there!") == 9 
Example 27
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    MIT License 5 votes vote down vote up
def test_strlen_approximate():
    lib = _Wconversion("int strlen(char *s);",
                       "#include <string.h>")
    assert lib.strlen(b"hi there!") == 9 
Example 28
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    MIT License 5 votes vote down vote up
def test_strlen_array_of_char():
    ffi = FFI()
    ffi.cdef("size_t strlen(char[]);")
    lib = ffi.verify("#include <string.h>")
    assert lib.strlen(b"hello") == 5 
Example 29
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    MIT License 5 votes vote down vote up
def test_longdouble():
    ffi = FFI()
    ffi.cdef("long double sinl(long double x);")
    lib = ffi.verify('#include <math.h>', libraries=lib_m)
    for input in [1.23,
                  ffi.cast("double", 1.23),
                  ffi.cast("long double", 1.23)]:
        x = lib.sinl(input)
        assert repr(x).startswith("<cdata 'long double'")
        assert (float(x) - math.sin(1.23)) < 1E-10 
Example 30
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    MIT License 5 votes vote down vote up
def test_funcptr_as_argument():
    ffi = FFI()
    ffi.cdef("""
        void qsort(void *base, size_t nel, size_t width,
            int (*compar)(const void *, const void *));
    """)
    ffi.verify("#include <stdlib.h>") 
Example 31
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    MIT License 5 votes vote down vote up
def test_array_as_argument():
    ffi = FFI()
    ffi.cdef("""
        size_t strlen(char string[]);
    """)
    ffi.verify("#include <string.h>") 
Example 32
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    MIT License 5 votes vote down vote up
def test_function_typedef():
    ffi = FFI()
    ffi.cdef("""
        typedef double func_t(double);
        func_t sin;
    """)
    lib = ffi.verify('#include <math.h>', libraries=lib_m)
    assert lib.sin(1.23) == math.sin(1.23) 
Example 33
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    MIT License 5 votes vote down vote up
def test_return_partial_struct():
    ffi = FFI()
    ffi.cdef("""
        typedef struct { int x; ...; } foo_t;
        foo_t foo(void);
    """)
    lib = ffi.verify("""
        typedef struct { int y, x; } foo_t;
        foo_t foo(void) { foo_t r = { 45, 81 }; return r; }
    """)
    h = lib.foo()
    assert ffi.sizeof(h) == 2 * ffi.sizeof("int")
    assert h.x == 81 
Example 34
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    MIT License 5 votes vote down vote up
def test_FILE_stored_in_stdout():
    if not sys.platform.startswith('linux'):
        py.test.skip("likely, we cannot assign to stdout")
    ffi = FFI()
    ffi.cdef("int printf(const char *, ...); FILE *setstdout(FILE *);")
    lib = ffi.verify("""
        #include <stdio.h>
        FILE *setstdout(FILE *f) {
            FILE *result = stdout;
            stdout = f;
            return result;
        }
    """)
    import os
    fdr, fdw = os.pipe()
    fw1 = os.fdopen(fdw, 'wb', 256)
    old_stdout = lib.setstdout(fw1)
    try:
        #
        fw1.write(b"X")
        r = lib.printf(b"hello, %d!\n", ffi.cast("int", 42))
        fw1.close()
        assert r == len("hello, 42!\n")
        #
    finally:
        lib.setstdout(old_stdout)
    #
    result = os.read(fdr, 256)
    os.close(fdr)
    # the 'X' might remain in the user-level buffer of 'fw1' and
    # end up showing up after the 'hello, 42!\n'
    assert result == b"Xhello, 42!\n" or result == b"hello, 42!\nX" 
Example 35
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    MIT License 5 votes vote down vote up
def test_string_to_voidp_arg():
    ffi = FFI()
    ffi.cdef("int myfunc(void *);")
    lib = ffi.verify("int myfunc(void *p) { return ((signed char *)p)[0]; }")
    res = lib.myfunc(b"hi!")
    assert res == ord(b"h")
    p = ffi.new("char[]", b"gah")
    res = lib.myfunc(p)
    assert res == ord(b"g")
    res = lib.myfunc(ffi.cast("void *", p))
    assert res == ord(b"g")
    res = lib.myfunc(ffi.cast("int *", p))
    assert res == ord(b"g") 
Example 36
Project: SwiftKitten   Author: johncsnyder   File: test_verify1.py    MIT License 5 votes vote down vote up
def test_simple_case():
    ffi = FFI()
    ffi.cdef("double sin(double x);")
    lib = ffi.verify('#include <math.h>', libraries=lib_m)
    assert lib.sin(1.23) == math.sin(1.23) 
Example 37
Project: SwiftKitten   Author: johncsnyder   File: test_verify1.py    MIT License 5 votes vote down vote up
def test_Wconversion_floating():
    lib = _Wconversion("float sin(double);",
                       "#include <math.h>", libraries=lib_m)
    res = lib.sin(1.23)
    assert res != math.sin(1.23)     # not exact, because of double->float
    assert abs(res - math.sin(1.23)) < 1E-5 
Example 38
Project: SwiftKitten   Author: johncsnyder   File: test_verify1.py    MIT License 5 votes vote down vote up
def test_Wconversion_float2int():
    _Wconversion("int sinf(float);",
                 "#include <math.h>", libraries=lib_m) 
Example 39
Project: SwiftKitten   Author: johncsnyder   File: test_verify1.py    MIT License 5 votes vote down vote up
def test_Wconversion_double2int():
    _Wconversion("int sin(double);",
                 "#include <math.h>", libraries=lib_m) 
Example 40
Project: SwiftKitten   Author: johncsnyder   File: test_verify1.py    MIT License 5 votes vote down vote up
def test_rounding_2():
    ffi = FFI()
    ffi.cdef("double sin(float x);")
    lib = ffi.verify('#include <math.h>', libraries=lib_m)
    res = lib.sin(1.23)
    assert res != math.sin(1.23)     # not exact, because of double->float
    assert abs(res - math.sin(1.23)) < 1E-5 
Example 41
Project: SwiftKitten   Author: johncsnyder   File: test_verify1.py    MIT License 5 votes vote down vote up
def test_strlen_exact():
    ffi = FFI()
    ffi.cdef("size_t strlen(const char *s);")
    lib = ffi.verify("#include <string.h>")
    assert lib.strlen(b"hi there!") == 9 
Example 42
Project: SwiftKitten   Author: johncsnyder   File: test_verify1.py    MIT License 5 votes vote down vote up
def test_strlen_approximate():
    lib = _Wconversion("int strlen(char *s);",
                       "#include <string.h>")
    assert lib.strlen(b"hi there!") == 9 
Example 43
Project: SwiftKitten   Author: johncsnyder   File: test_verify1.py    MIT License 5 votes vote down vote up
def test_strlen_array_of_char():
    ffi = FFI()
    ffi.cdef("size_t strlen(char[]);")
    lib = ffi.verify("#include <string.h>")
    assert lib.strlen(b"hello") == 5 
Example 44
Project: SwiftKitten   Author: johncsnyder   File: test_verify1.py    MIT License 5 votes vote down vote up
def test_longdouble():
    ffi = FFI()
    ffi.cdef("long double sinl(long double x);")
    lib = ffi.verify('#include <math.h>', libraries=lib_m)
    for input in [1.23,
                  ffi.cast("double", 1.23),
                  ffi.cast("long double", 1.23)]:
        x = lib.sinl(input)
        assert repr(x).startswith("<cdata 'long double'")
        assert (float(x) - math.sin(1.23)) < 1E-10 
Example 45
Project: SwiftKitten   Author: johncsnyder   File: test_verify1.py    MIT License 5 votes vote down vote up
def test_func_as_argument():
    ffi = FFI()
    ffi.cdef("""
        void qsort(void *base, size_t nel, size_t width,
            int compar(const void *, const void *));
    """)
    ffi.verify("#include <stdlib.h>") 
Example 46
Project: SwiftKitten   Author: johncsnyder   File: test_verify1.py    MIT License 5 votes vote down vote up
def test_array_as_argument():
    ffi = FFI()
    ffi.cdef("""
        size_t strlen(char string[]);
    """)
    ffi.verify("#include <string.h>") 
Example 47
Project: SwiftKitten   Author: johncsnyder   File: test_verify1.py    MIT License 5 votes vote down vote up
def test_function_typedef():
    ffi = FFI()
    ffi.cdef("""
        typedef double func_t(double);
        func_t sin;
    """)
    lib = ffi.verify('#include <math.h>', libraries=lib_m)
    assert lib.sin(1.23) == math.sin(1.23) 
Example 48
Project: SwiftKitten   Author: johncsnyder   File: test_verify1.py    MIT License 5 votes vote down vote up
def test_return_partial_struct():
    ffi = FFI()
    ffi.cdef("""
        typedef struct { int x; ...; } foo_t;
        foo_t foo(void);
    """)
    lib = ffi.verify("""
        typedef struct { int y, x; } foo_t;
        foo_t foo(void) { foo_t r = { 45, 81 }; return r; }
    """)
    h = lib.foo()
    assert ffi.sizeof(h) == 2 * ffi.sizeof("int")
    assert h.x == 81 
Example 49
Project: SwiftKitten   Author: johncsnyder   File: test_verify1.py    MIT License 5 votes vote down vote up
def test_relative_to():
    py.test.skip("not available")
    import tempfile, os
    from testing.udir import udir
    tmpdir = tempfile.mkdtemp(dir=str(udir))
    ffi = FFI()
    ffi.cdef("int foo(int);")
    f = open(os.path.join(tmpdir, 'foo.h'), 'w')
    f.write("int foo(int a) { return a + 42; }\n")
    f.close()
    lib = ffi.verify('#include "foo.h"',
                     include_dirs=['.'],
                     relative_to=os.path.join(tmpdir, 'x'))
    assert lib.foo(100) == 142 
Example 50
Project: SwiftKitten   Author: johncsnyder   File: test_verify1.py    MIT License 5 votes vote down vote up
def test_FILE_stored_in_stdout():
    if not sys.platform.startswith('linux'):
        py.test.skip("likely, we cannot assign to stdout")
    ffi = FFI()
    ffi.cdef("int printf(const char *, ...); FILE *setstdout(FILE *);")
    lib = ffi.verify("""
        #include <stdio.h>
        FILE *setstdout(FILE *f) {
            FILE *result = stdout;
            stdout = f;
            return result;
        }
    """)
    import os
    fdr, fdw = os.pipe()
    fw1 = os.fdopen(fdw, 'wb', 256)
    old_stdout = lib.setstdout(fw1)
    try:
        #
        fw1.write(b"X")
        r = lib.printf(b"hello, %d!\n", ffi.cast("int", 42))
        fw1.close()
        assert r == len("hello, 42!\n")
        #
    finally:
        lib.setstdout(old_stdout)
    #
    result = os.read(fdr, 256)
    os.close(fdr)
    # the 'X' might remain in the user-level buffer of 'fw1' and
    # end up showing up after the 'hello, 42!\n'
    assert result == b"Xhello, 42!\n" or result == b"hello, 42!\nX" 
Example 51
Project: SwiftKitten   Author: johncsnyder   File: test_verify1.py    MIT License 5 votes vote down vote up
def test_string_to_voidp_arg():
    ffi = FFI()
    ffi.cdef("int myfunc(void *);")
    lib = ffi.verify("int myfunc(void *p) { return ((signed char *)p)[0]; }")
    res = lib.myfunc(b"hi!")
    assert res == ord(b"h")
    p = ffi.new("char[]", b"gah")
    res = lib.myfunc(p)
    assert res == ord(b"g")
    res = lib.myfunc(ffi.cast("void *", p))
    assert res == ord(b"g")
    res = lib.myfunc(ffi.cast("int *", p))
    assert res == ord(b"g") 
Example 52
Project: SwiftKitten   Author: johncsnyder   File: test_verify1.py    MIT License 5 votes vote down vote up
def test_implicit_unicode_on_windows():
    from cffi import FFIError
    if sys.platform != 'win32':
        py.test.skip("win32-only test")
    ffi = FFI()
    e = py.test.raises(FFIError, ffi.cdef, "int foo(LPTSTR);")
    assert str(e.value) == ("The Windows type 'LPTSTR' is only available after"
                            " you call ffi.set_unicode()")
    for with_unicode in [True, False]:
        ffi = FFI()
        ffi.set_unicode(with_unicode)
        ffi.cdef("""
            DWORD GetModuleFileName(HMODULE hModule, LPTSTR lpFilename,
                                    DWORD nSize);
        """)
        lib = ffi.verify("""
            #include <windows.h>
        """, libraries=['Kernel32'])
        outbuf = ffi.new("TCHAR[]", 200)
        n = lib.GetModuleFileName(ffi.NULL, outbuf, 500)
        assert 0 < n < 500
        for i in range(n):
            #print repr(outbuf[i])
            assert ord(outbuf[i]) != 0
        assert ord(outbuf[n]) == 0
        assert ord(outbuf[0]) < 128     # should be a letter, or '\' 
Example 53
Project: SwiftKitten   Author: johncsnyder   File: test_recompiler.py    MIT License 5 votes vote down vote up
def test_math_sin():
    import math
    ffi = FFI()
    ffi.cdef("float sin(double); double cos(double);")
    lib = verify(ffi, 'test_math_sin', '#include <math.h>')
    assert lib.cos(1.43) == math.cos(1.43) 
Example 54
Project: SwiftKitten   Author: johncsnyder   File: test_recompiler.py    MIT License 5 votes vote down vote up
def test_math_sin_type():
    ffi = FFI()
    ffi.cdef("double sin(double);")
    lib = verify(ffi, 'test_math_sin_type', '#include <math.h>')
    # 'lib.sin' is typed as a <built-in method> object on lib
    assert ffi.typeof(lib.sin).cname == "double(*)(double)"
    # 'x' is another <built-in method> object on lib, made very indirectly
    x = type(lib).__dir__.__get__(lib)
    py.test.raises(TypeError, ffi.typeof, x)
    #
    # present on built-in functions on CPython; must be emulated on PyPy:
    assert lib.sin.__name__ == 'sin'
    assert lib.sin.__module__ == '_CFFI_test_math_sin_type'
    assert lib.sin.__doc__ == 'direct call to the C function of the same name' 
Example 55
Project: pams-skku   Author: HongBeenKim   File: planner.py    MIT License 5 votes vote down vote up
def init_cuda(self):
        # pycuda alloc
        drv.init()
        global context
        from pycuda.tools import make_default_context
        context = make_default_context()

        mod = SourceModule(r"""
                        #include <stdio.h>
                        #include <math.h>
                        #define PI 3.14159265
                        __global__ void detect(int data[][2], int* rad, int* range, unsigned char *frame, int *pcol) {
                                for(int r = 0; r < rad[0]; r++) {
                                    const int thetaIdx = threadIdx.x;
                                    const int theta = thetaIdx + range[0];
                                    int x = rad[0] + int(r * cos(theta * PI/180)) - 1;
                                    int y = rad[0] - int(r * sin(theta * PI/180)) - 1;
                                    if (data[thetaIdx][0] == 0) data[thetaIdx][1] = r;
                                    if (*(frame + y * *pcol + x) != 0) data[thetaIdx][0] = 1;
                                }
                        }
                        """)

        self.path = mod.get_function("detect")
        print("PLANNER: pycuda alloc end")
        # pycuda alloc end

        time.sleep(2) 
Example 56
Project: attention-lvcsr   Author: rizar   File: basic.py    MIT License 5 votes vote down vote up
def c_headers(self, c_compiler):
        l = ['<math.h>']
        # These includes are needed by Scalar and TensorType,
        # we declare them here and they will be re-used by TensorType
        l.append('<numpy/arrayobject.h>')
        l.append('<numpy/arrayscalars.h>')
        if config.lib.amdlibm and c_compiler.supports_amdlibm:
            l += ['<amdlibm.h>']
        return l 
Example 57
Project: PipelineC   Author: JulianKemmerer   File: SW_LIB.py    GNU General Public License v3.0 5 votes vote down vote up
def GENERATE_INT_N_HEADERS(max_bit_width=2048):
	# Do signed and unsigned two files
	for u in ["","u"]:
		text = "#pragma once\n"
		text += "#include <stdint.h>\n"
		min_width = 1
		#if u=="":
		#	min_width = 2
		for bitwidth in range(min_width,max_bit_width+1):
			standard_type = u + "int8_t"
			if bitwidth > 8:
				standard_type = u + "int16_t"
			if bitwidth > 16:
				standard_type = u + "int32_t"
			if bitwidth > 32:
				standard_type = u + "int64_t"
				
			the_type = u + "int" + str(bitwidth) + "_t"
			
			# Comment out standard types
			if the_type == standard_type:
				text += "//"
			
			text += "typedef " + standard_type + " " + the_type + ";\n"
	
		#print "GENERATE_INT_N_HEADERS"
		#print text
	
		filename = u + "intN_t.h"
		f=open(filename,"w")
		f.write(text)
		f.close() 
Example 58
Project: twinnet-asr   Author: dmitriy-serdyuk   File: basic.py    MIT License 5 votes vote down vote up
def c_headers(self, c_compiler):
        l = ['<math.h>']
        # These includes are needed by Scalar and TensorType,
        # we declare them here and they will be re-used by TensorType
        l.append('<numpy/arrayobject.h>')
        l.append('<numpy/arrayscalars.h>')
        if config.lib.amdlibm and c_compiler.supports_amdlibm:
            l += ['<amdlibm.h>']
        return l 
Example 59
Project: dependency-parser   Author: mzapotoczny   File: basic.py    MIT License 5 votes vote down vote up
def c_headers(self, c_compiler):
        l = ['<math.h>']
        # These includes are needed by Scalar and TensorType,
        # we declare them here and they will be re-used by TensorType
        l.append('<numpy/arrayobject.h>')
        l.append('<numpy/arrayscalars.h>')
        if config.lib.amdlibm and c_compiler.supports_amdlibm:
            l += ['<amdlibm.h>']
        return l 
Example 60
Project: D-VAE   Author: muhanzhang   File: basic.py    MIT License 4 votes vote down vote up
def c_code(self, node, name, inputs, outputs, sub):
        (x, y) = inputs
        (z,) = outputs
        t = node.inputs[0].type.upcast(*[i.type for i in node.inputs[1:]])
        if t in imap(str, discrete_types):
            x_div_y_pp = '(%(x)s / %(y)s)' % locals()
            x_div_y_mp = '((-%(x)s) / %(y)s)' % locals()
            x_mod_y_mp = 'THEANO_MACRO_MOD((-%(x)s), %(y)s)' % locals()
            x_div_y_pm = '(%(x)s / (-%(y)s))' % locals()
            x_mod_y_pm = 'THEANO_MACRO_MOD(%(x)s, (-%(y)s))' % locals()
            x_div_y_mm = '((-%(x)s) / (-%(y)s))' % locals()
        elif t in imap(str, float_types):
            # We need to call different functions of math.h
            # depending on the type
            if t == 'float32':
                floor = 'floorf'
                fmod = 'fmodf'
            elif t == 'float64':
                floor = 'floor'
                fmod = 'fmod'
            else:
                raise NotImplementedError('type not supported', t)

            x_div_y_pp = '%(floor)s(%(x)s / %(y)s)' % locals()
            x_div_y_mp = '%(floor)s((-%(x)s) / %(y)s)' % locals()
            x_mod_y_mp = '%(fmod)s((-%(x)s), %(y)s)' % locals()
            x_div_y_pm = '%(floor)s(%(x)s / (-%(y)s))' % locals()
            x_mod_y_pm = '%(fmod)s(%(x)s, (-%(y)s))' % locals()
            x_div_y_mm = '%(floor)s((-%(x)s) / (-%(y)s))' % locals()
        elif t in complex_types:
            raise self.complex_error
        else:
            raise NotImplementedError('type not supported', t)

        return dedent("""
            if (%(x)s < 0) {
                if (%(y)s < 0) {
                    %(z)s = %(x_div_y_mm)s;
                } else {
                    %(z)s = - %(x_div_y_mp)s - ((%(x_mod_y_mp)s == 0) ? 0 : 1);
                }
            } else {
                if (%(y)s < 0) {
                    %(z)s = - %(x_div_y_pm)s - ((%(x_mod_y_pm)s == 0) ? 0 : 1);
                } else {
                    %(z)s = %(x_div_y_pp)s;
                }
            }
            """) % locals() 
Example 61
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    MIT License 4 votes vote down vote up
def test_callback_indirection():
    ffi = FFI()
    ffi.cdef("""
        int (*python_callback)(int how_many, int *values);
        int (*const c_callback)(int,...);   /* pass this ptr to C routines */
        int some_c_function(int(*cb)(int,...));
    """)
    lib = ffi.verify("""
        #include <stdarg.h>
        #ifdef _WIN32
        #include <malloc.h>
        #define alloca _alloca
        #else
        # ifdef __FreeBSD__
        #  include <stdlib.h>
        # else
        #  include <alloca.h>
        # endif
        #endif
        static int (*python_callback)(int how_many, int *values);
        static int c_callback(int how_many, ...) {
            va_list ap;
            /* collect the "..." arguments into the values[] array */
            int i, *values = alloca((size_t)how_many * sizeof(int));
            va_start(ap, how_many);
            for (i=0; i<how_many; i++)
                values[i] = va_arg(ap, int);
            va_end(ap);
            return python_callback(how_many, values);
        }
        int some_c_function(int(*cb)(int,...)) {
            int result = cb(2, 10, 20);
            result += cb(3, 30, 40, 50);
            return result;
        }
    """)
    seen = []
    @ffi.callback("int(int, int*)")
    def python_callback(how_many, values):
        seen.append([values[i] for i in range(how_many)])
        return 42
    lib.python_callback = python_callback

    res = lib.some_c_function(lib.c_callback)
    assert res == 84
    assert seen == [[10, 20], [30, 40, 50]] 
Example 62
Project: SwiftKitten   Author: johncsnyder   File: test_verify1.py    MIT License 4 votes vote down vote up
def test_callback_indirection():
    ffi = FFI()
    ffi.cdef("""
        int (*python_callback)(int how_many, int *values);
        int (*const c_callback)(int,...);   /* pass this ptr to C routines */
        int some_c_function(int(*cb)(int,...));
    """)
    lib = ffi.verify("""
        #include <stdarg.h>
        #ifdef _WIN32
        #include <malloc.h>
        #define alloca _alloca
        #else
        # ifdef __FreeBSD__
        #  include <stdlib.h>
        # else
        #  include <alloca.h>
        # endif
        #endif
        static int (*python_callback)(int how_many, int *values);
        static int c_callback(int how_many, ...) {
            va_list ap;
            /* collect the "..." arguments into the values[] array */
            int i, *values = alloca((size_t)how_many * sizeof(int));
            va_start(ap, how_many);
            for (i=0; i<how_many; i++)
                values[i] = va_arg(ap, int);
            va_end(ap);
            return python_callback(how_many, values);
        }
        int some_c_function(int(*cb)(int,...)) {
            int result = cb(2, 10, 20);
            result += cb(3, 30, 40, 50);
            return result;
        }
    """)
    seen = []
    @ffi.callback("int(int, int*)")
    def python_callback(how_many, values):
        seen.append([values[i] for i in range(how_many)])
        return 42
    lib.python_callback = python_callback

    res = lib.some_c_function(lib.c_callback)
    assert res == 84
    assert seen == [[10, 20], [30, 40, 50]] 
Example 63
Project: attention-lvcsr   Author: rizar   File: basic.py    MIT License 4 votes vote down vote up
def c_code(self, node, name, inputs, outputs, sub):
        (x, y) = inputs
        (z,) = outputs
        t = node.inputs[0].type.upcast(*[i.type for i in node.inputs[1:]])
        if t in imap(str, discrete_types):
            x_div_y_pp = '(%(x)s / %(y)s)' % locals()
            x_div_y_mp = '((-%(x)s) / %(y)s)' % locals()
            x_mod_y_mp = 'THEANO_MACRO_MOD((-%(x)s), %(y)s)' % locals()
            x_div_y_pm = '(%(x)s / (-%(y)s))' % locals()
            x_mod_y_pm = 'THEANO_MACRO_MOD(%(x)s, (-%(y)s))' % locals()
            x_div_y_mm = '((-%(x)s) / (-%(y)s))' % locals()
        elif t in imap(str, float_types):
            # We need to call different functions of math.h
            # depending on the type
            if t == 'float32':
                floor = 'floorf'
                fmod = 'fmodf'
            elif t == 'float64':
                floor = 'floor'
                fmod = 'fmod'
            else:
                raise NotImplementedError('type not supported', t)

            x_div_y_pp = '%(floor)s(%(x)s / %(y)s)' % locals()
            x_div_y_mp = '%(floor)s((-%(x)s) / %(y)s)' % locals()
            x_mod_y_mp = '%(fmod)s((-%(x)s), %(y)s)' % locals()
            x_div_y_pm = '%(floor)s(%(x)s / (-%(y)s))' % locals()
            x_mod_y_pm = '%(fmod)s(%(x)s, (-%(y)s))' % locals()
            x_div_y_mm = '%(floor)s((-%(x)s) / (-%(y)s))' % locals()
        elif t in complex_types:
            raise self.complex_error
        else:
            raise NotImplementedError('type not supported', t)

        return dedent("""
            if (%(x)s < 0) {
                if (%(y)s < 0) {
                    %(z)s = %(x_div_y_mm)s;
                } else {
                    %(z)s = - %(x_div_y_mp)s - ((%(x_mod_y_mp)s == 0) ? 0 : 1);
                }
            } else {
                if (%(y)s < 0) {
                    %(z)s = - %(x_div_y_pm)s - ((%(x_mod_y_pm)s == 0) ? 0 : 1);
                } else {
                    %(z)s = %(x_div_y_pp)s;
                }
            }
            """) % locals() 
Example 64
Project: PipelineC   Author: JulianKemmerer   File: SW_LIB.py    GNU General Public License v3.0 4 votes vote down vote up
def GET_BIN_OP_MOD_FLOAT_N_C_CODE(partially_complete_logic, out_dir):
	# So there was this guy here trying to figure out the floating point implementation for modulo
	# Then the internet (of all people) chimes in and says modulo for floating point isn't actually part of standard C?
	# And that there are various fmod implementations for math.h
	# So me embracing the piece of shit (that I am) will implement mod in C too
	
	left_t = partially_complete_logic.wire_to_c_type[partially_complete_logic.inputs[0]]
	right_t = partially_complete_logic.wire_to_c_type[partially_complete_logic.inputs[1]]
	output_t = partially_complete_logic.wire_to_c_type[partially_complete_logic.outputs[0]]
	if not VHDL.WIRES_ARE_C_TYPE(partially_complete_logic.inputs + partially_complete_logic.outputs,"float",partially_complete_logic):
		print left_t, right_t, output_t
		print '''"left_t != "float" or  right_t != "float" output_t mod'''
		sys.exit(0)

	text = ""
	
	text += '''
#include "uintN_t.h"
#include "intN_t.h"
#include "''' + BIT_MANIP_HEADER_FILE + '''"

// Float div std_logic_vector in VHDL
''' + output_t + ''' ''' + partially_complete_logic.func_name + '''(''' + left_t + ''' left, ''' + right_t + ''' right)
{
	// Quotient
	float q;
	q = left / right;
	
	// Convert to int (floor?)
	// float max value = 3.402823466*10^38
	// log2(3.402823466*10^38) ~ 128 , int129
	int129_t q_int;
	q_int = q;
	
	// Partial quotient
	float partial;
	partial = (float)q_int * right;
	
	float remainder;
	remainder = left - partial;
	
	return remainder;
}
'''

	return text 
Example 65
Project: twinnet-asr   Author: dmitriy-serdyuk   File: basic.py    MIT License 4 votes vote down vote up
def c_code(self, node, name, inputs, outputs, sub):
        (x, y) = inputs
        (z,) = outputs
        t = node.inputs[0].type.upcast(*[i.type for i in node.inputs[1:]])
        if t in imap(str, discrete_types):
            x_div_y_pp = '(%(x)s / %(y)s)' % locals()
            x_div_y_mp = '((-%(x)s) / %(y)s)' % locals()
            x_mod_y_mp = 'THEANO_MACRO_MOD((-%(x)s), %(y)s)' % locals()
            x_div_y_pm = '(%(x)s / (-%(y)s))' % locals()
            x_mod_y_pm = 'THEANO_MACRO_MOD(%(x)s, (-%(y)s))' % locals()
            x_div_y_mm = '((-%(x)s) / (-%(y)s))' % locals()
        elif t in imap(str, float_types):
            # We need to call different functions of math.h
            # depending on the type
            if t == 'float32':
                floor = 'floorf'
                fmod = 'fmodf'
            elif t == 'float64':
                floor = 'floor'
                fmod = 'fmod'
            else:
                raise NotImplementedError('type not supported', t)

            x_div_y_pp = '%(floor)s(%(x)s / %(y)s)' % locals()
            x_div_y_mp = '%(floor)s((-%(x)s) / %(y)s)' % locals()
            x_mod_y_mp = '%(fmod)s((-%(x)s), %(y)s)' % locals()
            x_div_y_pm = '%(floor)s(%(x)s / (-%(y)s))' % locals()
            x_mod_y_pm = '%(fmod)s(%(x)s, (-%(y)s))' % locals()
            x_div_y_mm = '%(floor)s((-%(x)s) / (-%(y)s))' % locals()
        elif t in complex_types:
            raise self.complex_error
        else:
            raise NotImplementedError('type not supported', t)

        return dedent("""
            if (%(x)s < 0) {
                if (%(y)s < 0) {
                    %(z)s = %(x_div_y_mm)s;
                } else {
                    %(z)s = - %(x_div_y_mp)s - ((%(x_mod_y_mp)s == 0) ? 0 : 1);
                }
            } else {
                if (%(y)s < 0) {
                    %(z)s = - %(x_div_y_pm)s - ((%(x_mod_y_pm)s == 0) ? 0 : 1);
                } else {
                    %(z)s = %(x_div_y_pp)s;
                }
            }
            """) % locals() 
Example 66
Project: dependency-parser   Author: mzapotoczny   File: basic.py    MIT License 4 votes vote down vote up
def c_code(self, node, name, inputs, outputs, sub):
        (x, y) = inputs
        (z,) = outputs
        t = node.inputs[0].type.upcast(*[i.type for i in node.inputs[1:]])
        if t in imap(str, discrete_types):
            x_div_y_pp = '(%(x)s / %(y)s)' % locals()
            x_div_y_mp = '((-%(x)s) / %(y)s)' % locals()
            x_mod_y_mp = 'THEANO_MACRO_MOD((-%(x)s), %(y)s)' % locals()
            x_div_y_pm = '(%(x)s / (-%(y)s))' % locals()
            x_mod_y_pm = 'THEANO_MACRO_MOD(%(x)s, (-%(y)s))' % locals()
            x_div_y_mm = '((-%(x)s) / (-%(y)s))' % locals()
        elif t in imap(str, float_types):
            # We need to call different functions of math.h
            # depending on the type
            if t == 'float32':
                floor = 'floorf'
                fmod = 'fmodf'
            elif t == 'float64':
                floor = 'floor'
                fmod = 'fmod'
            else:
                raise NotImplementedError('type not supported', t)

            x_div_y_pp = '%(floor)s(%(x)s / %(y)s)' % locals()
            x_div_y_mp = '%(floor)s((-%(x)s) / %(y)s)' % locals()
            x_mod_y_mp = '%(fmod)s((-%(x)s), %(y)s)' % locals()
            x_div_y_pm = '%(floor)s(%(x)s / (-%(y)s))' % locals()
            x_mod_y_pm = '%(fmod)s(%(x)s, (-%(y)s))' % locals()
            x_div_y_mm = '%(floor)s((-%(x)s) / (-%(y)s))' % locals()
        elif t in complex_types:
            raise self.complex_error
        else:
            raise NotImplementedError('type not supported', t)

        return dedent("""
            if (%(x)s < 0) {
                if (%(y)s < 0) {
                    %(z)s = %(x_div_y_mm)s;
                } else {
                    %(z)s = - %(x_div_y_mp)s - ((%(x_mod_y_mp)s == 0) ? 0 : 1);
                }
            } else {
                if (%(y)s < 0) {
                    %(z)s = - %(x_div_y_pm)s - ((%(x_mod_y_pm)s == 0) ? 0 : 1);
                } else {
                    %(z)s = %(x_div_y_pp)s;
                }
            }
            """) % locals()