Перейти к содержимому

Define use math defines c что это

  • автор:

Математические константы

Корпорация Майкрософт предоставляет несколько предопределенных макросов препроцессора для общих математических констант.

Синтаксис

#define _USE_MATH_DEFINES // for C++ #include #define _USE_MATH_DEFINES // for C #include

Замечания

Определены символические обозначения для следующих величин:

Символ Expression Значение
M_E Д. 2.71828182845904523536
M_LOG2E log2(e) 1.44269504088896340736
M_LOG10E log10(e) 0.434294481903251827651
M_LN2 ln(2) 0.693147180559945309417
M_LN10 ln(10) 2.30258509299404568402
M_PI pi 3.14159265358979323846
M_PI_2 pi/2 1.57079632679489661923
M_PI_4 pi/4 0.785398163397448309616
M_1_PI 1/pi 0.318309886183790671538
M_2_PI 2/pi 0.636619772367581343076
M_2_SQRTPI 2/sqrt(pi) 1.12837916709551257390
M_SQRT2 sqrt(2) 1.41421356237309504880
M_SQRT1_2 1/sqrt(2) 0.707106781186547524401

Математические константы не определены в стандарте C/C++. Чтобы использовать их, сначала необходимо определить _USE_MATH_DEFINES , а затем включить или .

Файл включает в себя , когда проект построен в режиме выпуска. Если вы используете одну или несколько математических констант в проекте, который также включает , необходимо определить _USE_MATH_DEFINES перед включением .

Define use math defines c что это

work? How can you just magically define it like that and math constants will be available to you?

Is there something in cmath or math.h that checks if it is defined and based on that defines the math constants?

Also How do you look at the standard library files in Visual Studio?

Last edited on

Ok I googled it and figured out how it works.

It checks if you defined USE_MATH_DEFINES and based on that defines the constants.

It also checks if it is already DEFINED, I dont think it has to do this because pragma once and the include guards will prevent it from being included twice in a translation unit.

But here is the code that does that if anyone wants to see for future reference:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
 /* Define _USE_MATH_DEFINES before including math.h to expose these macro * definitions for common math constants. These are placed under an #ifdef * since these commonly-defined names are not part of the C/C++ standards. */ /* Definitions of useful mathematical constants * M_E - e * M_LOG2E - log2(e) * M_LOG10E - log10(e) * M_LN2 - ln(2) * M_LN10 - ln(10) * M_PI - pi * M_PI_2 - pi/2 * M_PI_4 - pi/4 * M_1_PI - 1/pi * M_2_PI - 2/pi * M_2_SQRTPI - 2/sqrt(pi) * M_SQRT2 - sqrt(2) * M_SQRT1_2 - 1/sqrt(2) */ /* _USE_MATH_DEFINES */ 

Математическая библиотека языков C и C++

В стандартную математическую библиотеку языка Си (а, значит, и C++) входит множество специальных математических функций, которые нужно знать и уметь использовать. Для того, чтобы использовать эти функции в своей программе, необходимо подключить заголовочный файл, содержащий описания этих функций, что делается строчкой в начале программы:

#include 

В языке C++ нужно указывать название заголовочного файла так:

#include

Функция от одного аргумента вызывается, например, так: sin(x) . Вместо числа x может быть любое число, переменная или выражение. Функция возвращает значение, которое можно вывести на экран, присвоить другой переменной или использовать в выражении:

y = sin(x);
printf("%lf", sqrt(2));
Функция Описание
Округление
round Округляет число по правилам арифметики, то есть round(1.5) == 2 , round(-1.5) == -2
floor Округляет число вниз (“пол”), при этом floor(1.5) == 1 , floor(-1.5) == -2
ceil Округляет число вверх (“потолок”), при этом ceil(1.5) == 2 , ceil(-1.5) == -1
trunc Округление в сторону нуля (отбрасывание дробной части), при этом trunc(1.5) == 1 , trunc(-1.5) == -1
fabs Модуль (абсолютная величина)
Корни, степени, логарифмы
sqrt Квадратный корень. Использование: sqrt(x)
cbrt Кубический корень. Использование: cbrt(x)
pow Возведение в степень, возвращает a b . Использование: pow(a,b)
exp Экспонента, возвращает e x . Использование: exp(x)
log Натуральный логарифм
log10 Десятичный логарифм
Тригонометрия
sin Синус угла, задаваемого в радианах
cos Косинус угла, задаваемого в радианах
tan Тангенс угла, задаваемого в радианах
asin Арксинус, возвращает значение в радианах
acos Арккосинус, возвращает значение в радианах
atan Арктангенс, возвращает значение в радианах

Также в файле cmath есть набор полезных числовых констант, например, константа M_PI хранит значение числа \(\pi\).

В компиляторе Visual C++ для использования этих констант необходимо объявить директиву препроцессора _USE_MATH_DEFINES перед подключения заголовочного файла cmath .

#define _USE_MATH_DEFINES #include

Деление действительных чисел

Для действительных чисел определены операции сложения, вычитания, умножения и деления.

При этом операция деления выполняется по-разному для переменных и констант целочисленного типа и для переменных и констант действительных типов. В первом случае деление производится нацело с отбрасыванием дробной части, во втором случае — деление производится точно и результатом является действительное число. Более точно, если делимое и делитель одновременно являются целочисленными константами или переменными целочисленных типов, то деление будет целочисленным, а если хотя бы одно из них действительное, то деление будет действительным. Например:

printf(«%lf\n», 10 / 3);
printf(«%lf\n», 10. / 3);
printf(«%lf\n», 10 / 3.);
printf(«%lf\n», 10. / 3.);

выведет 3 в первой строке и 3.33333 в остальных строках.

Результат выполнения деления не зависит от того, какой переменной будет присвоен результат. Если написать double a = 10 / 3; , то переменная a будет равна 3, так как деление 10/3 будет целочисленным, независимо от того, чему будет присвоен результат.

Fundamental types

void — type with an empty set of values. It is an incomplete type that cannot be completed (consequently, objects of type void are disallowed). There are no arrays of void , nor references to void . However, pointers to void and functions returning type void (procedures in other languages) are permitted.

[edit] std::nullptr_t (since C++11)

Defined in header
typedef decltype ( nullptr ) nullptr_t ;

std::nullptr_t is the type of the null pointer literal, nullptr . It is a distinct type that is not itself a pointer type or a pointer to member type. Its values are null pointer constant (see NULL ), and may be implicitly converted to any pointer and pointer to member type.

sizeof ( std:: nullptr_t ) is equal to sizeof ( void * ) .

[edit] Data models

The choices made by each implementation about the sizes of the fundamental types are collectively known as data model. Four data models found wide acceptance:

  • LP32 or 2/4/4 ( int is 16-bit, long and pointer are 32-bit)
  • Win16 API
  • ILP32 or 4/4/4 ( int , long , and pointer are 32-bit);
  • Win32 API
  • Unix and Unix-like systems (Linux, macOS)
  • LLP64 or 4/4/8 ( int and long are 32-bit, pointer is 64-bit)
  • Win32 API (also called the Windows API) with compilation target 64-bit ARM (AArch64) or x86-64 (a.k.a. x64)
  • LP64 or 4/8/8 ( int is 32-bit, long and pointer are 64-bit)
  • Unix and Unix-like systems (Linux, macOS)

Other models are very rare. For example, ILP64 (8/8/8: int , long , and pointer are 64-bit) only appeared in some early 64-bit Unix systems (e.g. UNICOS on Cray).

[edit] Integer types

[edit] Standard integer types

int — basic integer type. The keyword int may be omitted if any of the modifiers listed below are used. If no length modifiers are present, it’s guaranteed to have a width of at least 16 bits. However, on 32/64 bit systems it is almost exclusively guaranteed to have width of at least 32 bits (see below).

[edit] Modifiers

Modifies the basic integer type. Can be mixed in any order. Only one of each group can be present in type name.

  • Signedness:
  • Size:

Note: as with all type specifiers, any order is permitted: unsigned long long int and long int unsigned long name the same type.

[edit] Properties

The following table summarizes all available integer types and their properties in various common data models:

signed char
unsigned char
signed short
signed short int
unsigned short
unsigned short int
signed int
unsigned int
signed long
signed long int
unsigned long
unsigned long int
long long int
signed long long
signed long long int
unsigned long long
unsigned long long int

Note: integer arithmetic is defined differently for the signed and unsigned integer types. See arithmetic operators, in particular integer overflows.

std::size_t is the unsigned integer type of the result of the sizeof operator as well as the sizeof. operator and the alignof operator (since C++11) .

[edit] Extended integer types (since C++11)

The extended integer types are implementation-defined. Note that fixed width integer types are typically aliases of the standard integer types.

[edit] Boolean type

bool — type, capable of holding one of the two values: true or false . The value of sizeof ( bool ) is implementation defined and might differ from 1 .

[edit] Character types

signed char — type for signed character representation. unsigned char — type for unsigned character representation. Also used to inspect object representations (raw memory). char — type for character representation which can be most efficiently processed on the target system (has the same representation and alignment as either signed char or unsigned char , but is always a distinct type). Multibyte characters strings use this type to represent code units. For every value of type unsigned char in range [ ​ 0 ​ , 255 ] , converting the value to char and then back to unsigned char produces the original value. (since C++11) The signedness of char depends on the compiler and the target platform: the defaults for ARM and PowerPC are typically unsigned, the defaults for x86 and x64 are typically signed. wchar_t — type for wide character representation (see wide strings). It has the same size, signedness, and alignment as one of the integer types, but is a distinct type. In practice, it is 32 bits and holds UTF-32 on Linux and many other non-Windows systems, but 16 bits and holds UTF-16 code units on Windows. The standard used to require wchar_t to be large enough to represent any supported character code point. However, such requirement cannot be fulfilled on Windows, and thus it is considered as a defect and removed.

char16_t — type for UTF-16 character representation, required to be large enough to represent any UTF-16 code unit (16 bits). It has the same size, signedness, and alignment as std::uint_least16_t , but is a distinct type.

Besides the minimal bit counts, the C++ Standard guarantees that

1 == sizeof ( char ) ≤ sizeof ( short ) ≤ sizeof ( int ) ≤ sizeof ( long ) ≤ sizeof ( long long ) .

Note: this allows the extreme case in which bytes are sized 64 bits, all types (including char ) are 64 bits wide, and sizeof returns 1 for every type.

[edit] Floating-point types

[edit] Standard floating-point types

The following three types and their cv-qualified versions are collectively called standard floating-point types.

  • binary128 format is used by some HP-UX, SPARC, MIPS, ARM64, and z/OS implementations.
  • The most well known IEEE-754 binary64-extended format is x87 80-bit extended precision format. It is used by many x86 and x86-64 implementations (a notable exception is MSVC, which implements long double in the same format as double , i.e. binary64).
[edit] Extended floating-point types (since C++23)

The extended floating-point types are implementation-defined. They may include fixed width floating-point types.

[edit] Properties

Floating-point types may support special values:

  • infinity (positive and negative), see INFINITY
  • the negative zero, — 0.0 . It compares equal to the positive zero, but is meaningful in some arithmetic operations, e.g. 1.0 / 0.0 == INFINITY , but 1.0 /- 0.0 == — INFINITY ), and for some mathematical functions, e.g. sqrt (std::complex)
  • not-a-number (NaN), which does not compare equal with anything (including itself). Multiple bit patterns represent NaNs, see std::nan , NAN . Note that C++ takes no special notice of signalling NaNs other than detecting their support by std::numeric_limits::has_signaling_NaN , and treats all NaNs as quiet.

Real floating-point numbers may be used with arithmetic operators + , — , / , and * as well as various mathematical functions from . Both built-in operators and library functions may raise floating-point exceptions and set errno as described in math errhandling.

Floating-point expressions may have greater range and precision than indicated by their types, see FLT_EVAL_METHOD . Floating-point expressions may also be contracted, that is, calculated as if all intermediate values have infinite range and precision, see #pragma STDC FP_CONTRACT. Standard C++ does not restrict the accuracy of floating-point operations.

Some operations on floating-point numbers are affected by and modify the state of the floating-point environment (most notably, the rounding direction).

Implicit conversions are defined between real floating types and integer types.

See Limits of floating-point types and std::numeric_limits for additional details, limits, and properties of the floating-point types.

[edit] Range of values

The following table provides a reference for the limits of common numeric representations.

Prior to C++20, the C++ Standard allowed any signed integer representation, and the minimum guaranteed range of N-bit signed integers was from \(\scriptsize -(2^-1)\) -(2 N-1
-1) to \(\scriptsize +2^-1\) +2 N-1
-1 (e.g. −127 to 127 for a signed 8-bit type), which corresponds to the limits of ones’ complement or sign-and-magnitude.

However, all C++ compilers use two’s complement representation, and as of C++20, it is the only representation allowed by the standard, with the guaranteed range from \(\scriptsize -2^\) -2 N-1
to \(\scriptsize +2^-1\) +2 N-1
-1 (e.g. −128 to 127 for a signed 8-bit type).

8-bit ones’ complement and sign-and-magnitude representations for char have been disallowed since C++11 (via the resolution of CWG issue 1759), because a UTF-8 code unit of value 0x80 used in a UTF-8 string literal must be storable in a char type object.

The range for a floating-point type T is defined as follows:

  • The minimum guaranteed range is the most negative finite floating-point number representable in T through the most positive finite floating-point number representable in T .
  • If negative infinity is representable in T , the range of T is extended to all negative real numbers.
  • If positive infinity is representable in T , the range of T is extended to all positive real numbers.

Since negative and positive infinity are representable in ISO/IEC/IEEE 60559 formats, all real numbers lie within the range of representable values of a floating-point type adhering to ISO/IEC/IEEE 60559.

  • min subnormal:
    ± 1.401,298,4 · 10 −45
  • min normal:
    ± 1.175,494,3 · 10 −38
  • max:
    ± 3.402,823,4 · 10 38
  • min subnormal:
    ±0x1p−149
  • min normal:
    ±0x1p−126
  • max:
    ±0x1.fffffep+127
  • min subnormal:
    ± 4.940,656,458,412 · 10 −324
  • min normal:
    ± 2.225,073,858,507,201,4 · 10 −308
  • max:
    ± 1.797,693,134,862,315,7 · 10 308
  • min subnormal:
    ±0x1p−1074
  • min normal:
    ±0x1p−1022
  • max:
    ±0x1.fffffffffffffp+1023
  • min subnormal:
    ± 3.645,199,531,882,474,602,528
    · 10 −4951
  • min normal:
    ± 3.362,103,143,112,093,506,263
    · 10 −4932
  • max:
    ± 1.189,731,495,357,231,765,021
    · 10 4932
  • min subnormal:
    ±0x1p−16445
  • min normal:
    ±0x1p−16382
  • max:
    ±0x1.fffffffffffffffep+16383
  • min subnormal:
    ± 6.475,175,119,438,025,110,924,
    438,958,227,646,552,5 · 10 −4966
  • min normal:
    ± 3.362,103,143,112,093,506,262,
    677,817,321,752,602,6 · 10 −4932
  • max:
    ± 1.189,731,495,357,231,765,085,
    759,326,628,007,016,2 · 10 4932
  • min subnormal:
    ±0x1p−16494
  • min normal:
    ±0x1p−16382
  • max:
    ±0x1.ffffffffffffffffffffffffffff
    p+16383
  1. ↑ The object representation usually occupies 96/128 bits on 32/64-bit platforms respectively.

Note: actual (as opposed to guaranteed minimal) limits on the values representable by these types are available in C numeric limits interface and std::numeric_limits .

[edit] Notes

Feature-test macro Value Std Feature
__cpp_unicode_characters 200704L (C++11) New character types ( char16_t and char32_t )
__cpp_char8_t 201811L (C++20) char8_t
202207L (C++23) char8_t compatibility and portability fix (allow initialization of (unsigned) char arrays from UTF-8 string literals)

[edit] Keywords

[edit] Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
CWG 238 C++98 the constraints placed on a floating-point implementation was unspecified specified as
no constraint
CWG 1759 C++11 char is not guaranteed to be able to represent UTF-8 code unit 0x80 guaranteed
CWG 2723 C++98 the ranges of representable values for floating-point types were not specified specified
P2460R2 C++98 wchar_t was required to be able to represent distinct codes for all members
of the largest extended character set specified among the supported locales
not required

[edit] See also

  • the C++ type system overview
  • const-volatility (cv) specifiers and qualifiers
  • storage duration specifiers

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *