Python math.h() Examples

The following are 30 code examples for showing how to use math.h(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module math , or try the search function .

Example 1
Project: m2cgen   Author: BayesWitnesses   File: test_fallback_expressions.py    License: MIT License 6 votes vote down vote up
def test_abs_fallback_expr():
    expr = ast.AbsExpr(ast.NumVal(-2.0))

    interpreter = CInterpreter()
    interpreter.abs_function_name = NotImplemented

    expected_code = """
#include <math.h>
double score(double * input) {
    double var0;
    double var1;
    var1 = -2.0;
    if ((var1) < (0)) {
        var0 = (0.0) - (var1);
    } else {
        var0 = var1;
    }
    return var0;
}
"""

    assert_code_equal(interpreter.interpret(expr), expected_code) 
Example 2
Project: SwiftKitten   Author: johncsnyder   File: test_zdistutils.py    License: 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 3
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    License: 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 4
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    License: 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 5
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    License: 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 6
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    License: 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 7
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    License: 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 8
Project: SwiftKitten   Author: johncsnyder   File: test_verify1.py    License: 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 9
Project: SwiftKitten   Author: johncsnyder   File: test_verify1.py    License: 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 10
Project: SwiftKitten   Author: johncsnyder   File: test_verify1.py    License: 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 11
Project: SwiftKitten   Author: johncsnyder   File: test_recompiler.py    License: 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 12
Project: ctypesgen   Author: davidjamesca   File: testsuite.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def setUp(self):
        """NOTE this is called once for each test* method
        (it is not called once per class).
        FIXME This is slightly inefficient as it is called *way* more times than it needs to be.
        """
        header_str = """
#include <math.h>
#define sin_plus_y(x,y) (sin(x) + (y))
"""
        if sys.platform == "win32":
            # pick something from %windir%\system32\msvc*dll that include stdlib
            libraries = ["msvcrt.dll"]
            libraries = ["msvcrt"]
        elif sys.platform.startswith("linux"):
            libraries = ["libm.so.6"]
        else:
            libraries = ["libc"]
        self.module, output = ctypesgentest.test(header_str, libraries=libraries, all_headers=True) 
Example 13
Project: D-VAE   Author: muhanzhang   File: basic.py    License: 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 14
Project: SwiftKitten   Author: johncsnyder   File: test_zdistutils.py    License: 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 15
Project: SwiftKitten   Author: johncsnyder   File: test_zdistutils.py    License: 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 16
Project: SwiftKitten   Author: johncsnyder   File: test_zdistutils.py    License: 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 17
Project: SwiftKitten   Author: johncsnyder   File: test_zdistutils.py    License: 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 18
Project: SwiftKitten   Author: johncsnyder   File: test_zdistutils.py    License: 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 19
Project: SwiftKitten   Author: johncsnyder   File: test_zdistutils.py    License: 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 20
Project: SwiftKitten   Author: johncsnyder   File: test_zdistutils.py    License: 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 21
Project: SwiftKitten   Author: johncsnyder   File: test_zdistutils.py    License: 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 22
Project: SwiftKitten   Author: johncsnyder   File: test_zdistutils.py    License: 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 23
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    License: 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 24
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    License: 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 25
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    License: MIT License 5 votes vote down vote up
def test_Wconversion_float2int():
    _Wconversion("int sinf(float);",
                 "#include <math.h>", libraries=lib_m) 
Example 26
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    License: MIT License 5 votes vote down vote up
def test_Wconversion_double2int():
    _Wconversion("int sin(double);",
                 "#include <math.h>", libraries=lib_m) 
Example 27
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    License: 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 28
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    License: 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 29
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    License: 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 30
Project: SwiftKitten   Author: johncsnyder   File: test_verify.py    License: 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