Главная » Просмотр файлов » Стандарт языка Си С99 TC

Стандарт языка Си С99 TC (1113411), страница 77

Файл №1113411 Стандарт языка Си С99 TC (Стандарт языка Си С99 + TC) 77 страницаСтандарт языка Си С99 TC (1113411) страница 772019-04-24СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 77)

Whether conversion of non-integer floating values whoseintegral part is within the range of the integer type raises the ‘‘inexact’’ floating-pointexception is unspecified.310)F.5 Binary-decimal conversion1Conversion from the widest supported IEC 60559 format to decimal withDECIMAL_DIG digits and back is the identity function.311)2Conversions involving IEC 60559 formats follow all pertinent recommended practice. Inparticular, conversion between any supported IEC 60559 format and decimal withDECIMAL_DIG or fewer significant digits is correctly rounded (honoring the currentrounding mode), which assures that conversion from the widest supported IEC 60559format to decimal with DECIMAL_DIG digits and back is the identity function.3Functions such as strtod that convert character sequences to floating types honor therounding direction. Hence, if the rounding direction might be upward or downward, theimplementation cannot convert a minus-signed sequence by negating the convertedunsigned sequence.310) ANSI/IEEE 854, but not IEC 60559 (ANSI/IEEE 754), directly specifies that floating-to-integerconversions raise the ‘‘inexact’’ floating-point exception for non-integer in-range values.

In thosecases where it matters, library functions can be used to effect such conversions with or without raisingthe ‘‘inexact’’ floating-point exception. See rint, lrint, llrint, and nearbyint in<math.h>.311) If the minimum-width IEC 60559 extended format (64 bits of precision) is supported,DECIMAL_DIG shall be at least 21.

If IEC 60559 double (53 bits of precision) is the widestIEC 60559 format supported, then DECIMAL_DIG shall be at least 17. (By contrast, LDBL_DIG andDBL_DIG are 18 and 15, respectively, for these formats.)§F.5IEC 60559 floating-point arithmetic447ISO/IEC 9899:TC3Committee Draft — Septermber 7, 2007WG14/N1256F.6 Contracted expressions1A contracted expression treats infinities, NaNs, signed zeros, subnormals, and therounding directions in a manner consistent with the basic arithmetic operations coveredby IEC 60559.Recommended practice2A contracted expression should raise floating-point exceptions in a manner generallyconsistent with the basic arithmetic operations.

A contracted expression should deliverthe same value as its uncontracted counterpart, else should be correctly rounded (once).F.7 Floating-point environment1The floating-point environment defined in <fenv.h> includes the IEC 60559 floatingpoint exception status flags and directed-rounding control modes.

It includes alsoIEC 60559 dynamic rounding precision and trap enablement modes, if theimplementation supports them.312)F.7.1 Environment management1IEC 60559 requires that floating-point operations implicitly raise floating-point exceptionstatus flags, and that rounding control modes can be set explicitly to affect result values offloating-point operations. When the state for the FENV_ACCESS pragma (defined in<fenv.h>) is ‘‘on’’, these changes to the floating-point state are treated as side effectswhich respect sequence points.313)F.7.2 Translation1During translation the IEC 60559 default modes are in effect:— The rounding direction mode is rounding to nearest.— The rounding precision mode (if supported) is set so that results are not shortened.— Trapping or stopping (if supported) is disabled on all floating-point exceptions.Recommended practice2The implementation should produce a diagnostic message for each translation-time312) This specification does not require dynamic rounding precision nor trap enablement modes.313) If the state for the FENV_ACCESS pragma is ‘‘off’’, the implementation is free to assume the floatingpoint control modes will be the default ones and the floating-point status flags will not be tested,which allows certain optimizations (see F.8).448IEC 60559 floating-point arithmetic§F.7.2WG14/N1256Committee Draft — Septermber 7, 2007ISO/IEC 9899:TC3floating-point exception, other than ‘‘inexact’’;314) the implementation should thenproceed with the translation of the program.F.7.3 Execution1At program startup the floating-point environment is initialized as prescribed byIEC 60559:— All floating-point exception status flags are cleared.— The rounding direction mode is rounding to nearest.— The dynamic rounding precision mode (if supported) is set so that results are notshortened.— Trapping or stopping (if supported) is disabled on all floating-point exceptions.F.7.4 Constant expressions1An arithmetic constant expression of floating type, other than one in an initializer for anobject that has static storage duration, is evaluated (as if) during execution; thus, it isaffected by any operative floating-point control modes and raises floating-pointexceptions as required by IEC 60559 (provided the state for the FENV_ACCESS pragmais ‘‘on’’).315)2EXAMPLE#include <fenv.h>#pragma STDC FENV_ACCESS ONvoid f(void){float w[] = { 0.0/0.0 };static float x = 0.0/0.0;float y = 0.0/0.0;double z = 0.0/0.0;/* ...

*/}3////////raises an exceptiondoes not raise an exceptionraises an exceptionraises an exceptionFor the static initialization, the division is done at translation time, raising no (execution-time) floatingpoint exceptions. On the other hand, for the three automatic initializations the invalid division occurs at314) As floating constants are converted to appropriate internal representations at translation time, theirconversion is subject to default rounding modes and raises no execution-time floating-point exceptions(even where the state of the FENV_ACCESS pragma is ‘‘on’’). Library functions, for examplestrtod, provide execution-time conversion of numeric strings.315) Where the state for the FENV_ACCESS pragma is ‘‘on’’, results of inexact expressions like 1.0/3.0are affected by rounding modes set at execution time, and expressions such as 0.0/0.0 and1.0/0.0 generate execution-time floating-point exceptions.

The programmer can achieve theefficiency of translation-time evaluation through static initialization, such asconst static double one_third = 1.0/3.0;§F.7.4IEC 60559 floating-point arithmetic449ISO/IEC 9899:TC3Committee Draft — Septermber 7, 2007WG14/N1256execution time.F.7.5 Initialization1All computation for automatic initialization is done (as if) at execution time; thus, it isaffected by any operative modes and raises floating-point exceptions as required byIEC 60559 (provided the state for the FENV_ACCESS pragma is ‘‘on’’). All computationfor initialization of objects that have static storage duration is done (as if) at translationtime.2EXAMPLE#include <fenv.h>#pragma STDC FENV_ACCESS ONvoid f(void){float u[] = { 1.1e75 };static float v = 1.1e75;float w = 1.1e75;double x = 1.1e75;float y = 1.1e75f;long double z = 1.1e75;/* ...

*/}3////////////raises exceptionsdoes not raise exceptionsraises exceptionsmay raise exceptionsmay raise exceptionsdoes not raise exceptionsThe static initialization of v raises no (execution-time) floating-point exceptions because its computation isdone at translation time. The automatic initialization of u and w require an execution-time conversion tofloat of the wider value 1.1e75, which raises floating-point exceptions. The automatic initializationsof x and y entail execution-time conversion; however, in some expression evaluation methods, theconversions is not to a narrower format, in which case no floating-point exception is raised.316) Theautomatic initialization of z entails execution-time conversion, but not to a narrower format, so no floatingpoint exception is raised.

Note that the conversions of the floating constants 1.1e75 and 1.1e75f totheir internal representations occur at translation time in all cases.316) Use of float_t and double_t variables increases the likelihood of translation-time computation.For example, the automatic initializationdouble_t x = 1.1e75;could be done at translation time, regardless of the expression evaluation method.450IEC 60559 floating-point arithmetic§F.7.5WG14/N1256Committee Draft — Septermber 7, 2007ISO/IEC 9899:TC3F.7.6 Changing the environment1Operations defined in 6.5 and functions and macros defined for the standard librarieschange floating-point status flags and control modes just as indicated by theirspecifications (including conformance to IEC 60559). They do not change flags or modes(so as to be detectable by the user) in any other cases.2If the argument to the feraiseexcept function in <fenv.h> represents IEC 60559valid coincident floating-point exceptions for atomic operations (namely ‘‘overflow’’ and‘‘inexact’’, or ‘‘underflow’’ and ‘‘inexact’’), then ‘‘overflow’’ or ‘‘underflow’’ is raisedbefore ‘‘inexact’’.F.8 Optimization1This section identifies code transformations that might subvert IEC 60559-specifiedbehavior, and others that do not.F.8.1 Global transformations1Floating-point arithmetic operations and external function calls may entail side effectswhich optimization shall honor, at least where the state of the FENV_ACCESS pragma is‘‘on’’.

The flags and modes in the floating-point environment may be regarded as globalvariables; floating-point operations (+, *, etc.) implicitly read the modes and write theflags.2Concern about side effects may inhibit code motion and removal of seemingly uselesscode. For example, in#include <fenv.h>#pragma STDC FENV_ACCESS ONvoid f(double x){/* ... */for (i = 0; i < n; i++) x + 1;/* ... */}x + 1 might raise floating-point exceptions, so cannot be removed.

And since the loopbody might not execute (maybe 0 ≥ n), x + 1 cannot be moved out of the loop. (Ofcourse these optimizations are valid if the implementation can rule out the nettlesomecases.)3This specification does not require support for trap handlers that maintain informationabout the order or count of floating-point exceptions. Therefore, between function calls,floating-point exceptions need not be precise: the actual order and number of occurrencesof floating-point exceptions (> 1) may vary from what the source code expresses.

Thus,the preceding loop could be treated as§F.8.1IEC 60559 floating-point arithmetic451ISO/IEC 9899:TC3Committee Draft — Septermber 7, 2007WG14/N1256if (0 < n) x + 1;F.8.2 Expression transformations1x / 2 ↔ x * 0.5Although similar transformations involving inexactconstants generally do not yield numerically equivalentexpressions, if the constants are exact then suchtransformations can be made on IEC 60559 machinesand others that round perfectly.1 * x and x / 1 → xThe expressions 1 * x, x / 1, and x are equivalent(on IEC 60559 machines, among others).317)x / x → 1.0The expressions x / x and 1.0 are not equivalent if xcan be zero, infinite, or NaN.x − y ↔ x + (−y)The expressions x − y, x + (−y), and (−y) + xare equivalent (on IEC 60559 machines, among others).x − y ↔ −(y − x)The expressions x − y and −(y − x) are notequivalent because 1 − 1 is +0 but −(1 − 1) is −0 (in thedefault rounding direction).318)x − x → 0.0The expressions x − x and 0.0 are not equivalent ifx is a NaN or infinite.0 * x → 0.0The expressions 0 * x and 0.0 are not equivalent ifx is a NaN, infinite, or −0.x + 0→xThe expressions x + 0 and x are not equivalent if x is−0, because (−0) + (+0) yields +0 (in the defaultrounding direction), not −0.x − 0→x(+0) − (+0) yields −0 when rounding is downward(toward −∞), but +0 otherwise, and (−0) − (+0) alwaysyields −0; so, if the state of the FENV_ACCESS pragmais ‘‘off’’, promising default rounding, then theimplementation can replace x − 0 by x, even if x317) Strict support for signaling NaNs — not required by this specification — would invalidate these andother transformations that remove arithmetic operators.318) IEC 60559 prescribes a signed zero to preserve mathematical identities across certain discontinuities.Examples include:1/(1/ ± ∞) is ± ∞andconj(csqrt(z)) is csqrt(conj(z)),for complex z.452IEC 60559 floating-point arithmetic§F.8.2WG14/N1256Committee Draft — Septermber 7, 2007ISO/IEC 9899:TC3might be zero.−x ↔ 0 − xThe expressions −x and 0 − x are not equivalent if xis +0, because −(+0) yields −0, but 0 − (+0) yields +0(unless rounding is downward).F.8.3 Relational operators1x != x → falseThe statement x != x is true if x is a NaN.x == x → trueThe statement x == x is false if x is a NaN.x < y → isless(x,y)(and similarly for <=, >, >=) Though numericallyequal, these expressions are not equivalent because ofside effects when x or y is a NaN and the state of theFENV_ACCESS pragma is ‘‘on’’.

Характеристики

Тип файла
PDF-файл
Размер
3,61 Mb
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6418
Авторов
на СтудИзбе
307
Средний доход
с одного платного файла
Обучение Подробнее