Sqrt domain error c builder

Sqrt domain error c builder Группа: Участник Сообщений: 9 Люди помогите пожалуйсто. Есть такой код: CODE Q = b-L1*sin(FI); P = a-L1*cos(FI); F = (P*P+Q*Q+L2*L2-L3*L3)/(2*L2); PSI = 2*atan((Q+sborka*sqrt(Q*Q+P*P-F*F))/(P+F)); KSI = acos((L2*cos(PSI)+L1*cos(FI)-a)/(L3)); Если выражение под корнем CODE sqrt(Q*Q+P*P-F*F) то возникает ошибка программы с текстом: SQRT: DOMAIN error, а затем ACOS: DOMAIN error. Как можно подавить […]

Содержание

  1. Sqrt domain error c builder
  2. FLP32-C. Prevent or detect domain and range errors in math functions
  3. Domain and Pole Checking
  4. Range Checking
  5. Subnormal Numbers
  6. Noncompliant Code Example ( sqrt() )
  7. Compliant Solution ( sqrt() )
  8. Noncompliant Code Example ( sinh() , Range Errors)
  9. Compliant Solution ( sinh() , Range Errors)
  10. Noncompliant Code Example ( pow() )
  11. Compliant Solution ( pow() )
  12. Noncompliant Code Example ( asin() , Subnormal Number)
  13. Compliant Solution ( asin() , Subnormal Number)
  14. Risk Assessment

Sqrt domain error c builder

Группа: Участник
Сообщений: 9

Люди помогите пожалуйсто.
Есть такой код:

CODE
Q = b-L1*sin(FI);
P = a-L1*cos(FI);
F = (P*P+Q*Q+L2*L2-L3*L3)/(2*L2);

PSI = 2*atan((Q+sborka*sqrt(Q*Q+P*P-F*F))/(P+F));
KSI = acos((L2*cos(PSI)+L1*cos(FI)-a)/(L3));

Если выражение под корнем

то возникает ошибка программы с текстом:
SQRT: DOMAIN error,
а затем
ACOS: DOMAIN error.

Как можно подавить эти сообщения. Необходимо, что бы программа не обращала внимание на эти ошибки. Георгий

Отправлено: 19.04.2005, 23:25

Группа: Модератор
Сообщений: 874

пара try catch не помогает? FataLL

Отправлено: 20.04.2005, 02:53

Группа: Участник
Сообщений: 37

Блин, а просто

CODE
double dNum = .
if( dNum >= 0.0 )
<
sqrt.
>

не канает? Дожили.

Отредактировано FataLL — 20/04/2005, 02:53 ozx

Отправлено: 20.04.2005, 09:51

Группа: Участник
Сообщений: 9

пробовал

CODE
try
<
sqrt.
>
catch(. )
<
>

Но все равно, ошибки возникают. Может я что-то ни то делаю.

А по-поводу второго варианта, это второе что мне пришло в голову, после try catch, Но я хочу понять, почему, ошибки не подавляются.

Возможно это из-за того что в блоке try я разместил много формул. Хотя я сомневаюсь. FataLL

Отправлено: 21.04.2005, 11:40

Группа: Участник
Сообщений: 37

Копни здесь попробуй:

exp(x) , exp2(x) , expm1(x)

log(x) , log10(x) , log2(x)

x != 0 && !isinf(x) && !isnan(x)

scalbn(x, n) , scalbln(x, n)

x > 0 || (x == 0 && y > 0) ||
( x is an integer)

x != 0 && ! ( x is an integer)

fmod(x, y) , remainder(x, y) ,
remquo(x, y, quo)

nextafter(x, y) ,
nexttoward(x, y)

Domain and Pole Checking

The most reliable way to handle domain and pole errors is to prevent them by checking arguments beforehand, as in the following exemplar:

Range Checking

Programmers usually cannot prevent range errors, so the most reliable way to handle them is to detect when they have occurred and act accordingly.

The exact treatment of error conditions from math functions is tedious. The C Standard, 7.12.1 [ISO/IEC 9899:2011], defines the following behavior for floating-point overflow:

A floating result overflows if the magnitude of the mathematical result is finite but so large that the mathematical result cannot be represented without extraordinary roundoff error in an object of the specified type. If a floating result overflows and default rounding is in effect, then the function returns the value of the macro HUGE_VAL , HUGE_VALF , or HUGE_VALL according to the return type, with the same sign as the correct value of the function; if the integer expression math_errhandling & MATH_ERRNO is nonzero, the integer expression errno acquires the value ERANGE ; if the integer expression math_errhandling & MATH_ERREXCEPT is nonzero, the «overflow» floating-point exception is raised.

It is preferable not to check for errors by comparing the returned value against HUGE_VAL or 0 for several reasons:

  • These are, in general, valid (albeit unlikely) data values.
  • Making such tests requires detailed knowledge of the various error returns for each math function.
  • Multiple results aside from HUGE_VAL and 0 are possible, and programmers must know which are possible in each case.
  • Different versions of the library have varied in their error-return behavior.

It can be unreliable to check for math errors using errno because an implementation might not set errno . For real functions, the programmer determines if the implementation sets errno by checking whether math_errhandling & MATH_ERRNO is nonzero. For complex functions, the C Standard, 7.3.2, paragraph 1, simply states that «an implementation may set errno but is not required to» [ISO/IEC 9899:2011].

The obsolete System V Interface Definition (SVID3) [UNIX 1992] provides more control over the treatment of errors in the math library. The programmer can define a function named matherr() that is invoked if errors occur in a math function. This function can print diagnostics, terminate the execution, or specify the desired return value. The matherr() function has not been adopted by C or POSIX, so it is not generally portable.

The following error-handing template uses C Standard functions for floating-point errors when the C macro math_errhandling is defined and indicates that they should be used; otherwise, it examines errno :

See FLP03-C. Detect and handle floating-point errors for more details on how to detect floating-point errors.

Subnormal Numbers

A subnormal number is a nonzero number that does not use all of its precision bits [ IEEE 754 2006 ]. These numbers can be used to represent values that are closer to 0 than the smallest normal number (one that uses all of its precision bits). However, the asin() , asinh() , atan() , atanh() , and erf() functions may produce range errors, specifically when passed a subnormal number. When evaluated with a subnormal number, these functions can produce an inexact, subnormal value, which is an underflow error. The C Standard, 7.12.1, paragraph 6 [ISO/IEC 9899:2011], defines the following behavior for floating-point underflow:

The result underflows if the magnitude of the mathematical result is so small that the mathematical result cannot be represented, without extraordinary roundoff error, in an object of the specified type. If the result underflows, the function returns an implementation-defined value whose magnitude is no greater than the smallest normalized positive number in the specified type; if the integer expression math_errhandling & MATH_ERRNO is nonzero, whether errno acquires the value ERANGE is implementation-defined; if the integer expression math_errhandling & MATH_ERREXCEPT is nonzero, whether the ‘‘underflow’’ floating-point exception is raised is implementation-defined.

Implementations that support floating-point arithmetic but do not support subnormal numbers, such as IBM S/360 hex floating-point or nonconforming IEEE-754 implementations that skip subnormals (or support them by flushing them to zero), can return a range error when calling one of the following families of functions with the following arguments:

  • fmod ((min+subnorm), min)
  • remainder ((min+ subnorm ), min)
  • remquo ((min+ subnorm ), min, quo)

where min is the minimum value for the corresponding floating point type and subnorm is a subnormal value.

If Annex F is supported and subnormal results are supported, the returned value is exact and a range error cannot occur. The C Standard, F.10.7.1 [ISO/IEC 9899:2011], specifies the following for the fmod() , remainder() , and remquo() functions:

When subnormal results are supported, the returned value is exact and is independent of the current rounding direction mode.

Annex F, subclause F.10.7.2, paragraph 2, and subclause F.10.7.3, paragraph 2, of the C Standard identify when subnormal results are supported.

Noncompliant Code Example ( sqrt() )

This noncompliant code example determines the square root of x :

However, this code may produce a domain error if x is negative.

Compliant Solution ( sqrt() )

Because this function has domain errors but no range errors, bounds checking can be used to prevent domain errors:

Noncompliant Code Example ( sinh() , Range Errors)

This noncompliant code example determines the hyperbolic sine of x :

This code may produce a range error if x has a very large magnitude.

Compliant Solution ( sinh() , Range Errors)

Because this function has no domain errors but may have range errors, the programmer must detect a range error and act accordingly:

Noncompliant Code Example ( pow() )

This noncompliant code example raises x to the power of y :

This code may produce a domain error if x is negative and y is not an integer value or if x is 0 and y is 0. A domain error or pole error may occur if x is 0 and y is negative, and a range error may occur if the result cannot be represented as a double .

Compliant Solution ( pow() )

Because the pow() function can produce domain errors, pole errors, and range errors, the programmer must first check that x and y lie within the proper domain and do not generate a pole error and then detect whether a range error occurs and act accordingly:

Noncompliant Code Example ( asin() , Subnormal Number)

This noncompliant code example determines the inverse sine of x :

Compliant Solution ( asin() , Subnormal Number)

Because this function has no domain errors but may have range errors, the programmer must detect a range error and act accordingly:

Risk Assessment

Failure to prevent or detect domain and range errors in math functions may cause unexpected results.

Источник

Adblock
detector

CODE
#include
#include
#include

int _matherr (struct _exception *a)
<
if (a->type == DOMAIN)
if (!strcmp(a->name,»sqrt»)) <
a->retval = sqrt (-(a->arg1));
return 1;
>
return 0;
>

Источник

FLP32-C. Prevent or detect domain and range errors in math functions

The C Standard, 7.12.1 [ISO/IEC 9899:2011], defines three types of errors that relate specifically to math functions in . Paragraph 2 states

A domain error occurs if an input argument is outside the domain over which the mathematical function is defined.

Paragraph 3 states

A pole error (also known as a singularity or infinitary) occurs if the mathematical function has an exact infinite result as the finite input argument(s) are approached in the limit.

Paragraph 4 states

A range error occurs if the mathematical result of the function cannot be represented in an object of the specified type, due to extreme magnitude.

An example of a domain error is the square root of a negative number, such as sqrt(-1.0) , which has no meaning in real arithmetic. Contrastingly, 10 raised to the 1-millionth power, pow(10., 1e6) , cannot be represented in many floating-point implementations because of the limited range of the type double and consequently constitutes a range error. In both cases, the function will return some value, but the value returned is not the correct result of the computation. An example of a pole error is log(0.0) , which results in negative infinity.

Programmers can prevent domain and pole errors by carefully bounds-checking the arguments before calling mathematical functions and taking alternative action if the bounds are violated.

Range errors usually cannot be prevented because they are dependent on the implementation of floating-point numbers as well as on the function being applied. Instead of preventing range errors, programmers should attempt to detect them and take alternative action if a range error occurs.

The following table lists the double forms of standard mathematical functions, along with checks that should be performed to ensure a proper input domain, and indicates whether they can also result in range or pole errors, as reported by the C Standard. Both float and long double forms of these functions also exist but are omitted from the table for brevity. If a function has a specific domain over which it is defined, the programmer must check its input values. The programmer must also check for range errors where they might occur. The standard math functions not listed in this table, such as fabs() , have no domain restrictions and cannot result in range or pole errors.

No
asin(x) -1 Yes No
atan(x) None Yes No

    msm.ru

    Нравится ресурс?

    Помоги проекту!

    [!] Как относитесь к модерированию на этом форуме? Выскажите свое мнение здесь

    >
    Сообщение «sqrt: DOMAIN error»
    , Как найти грабли?

    • Подписаться на тему
    • Сообщить другу
    • Скачать/распечатать тему



    Сообщ.
    #1

    ,
    08.02.07, 10:29

      Senior Member

      ****

      Рейтинг (т): 23

      Дело в следующем: в проге есть несколько вызовов функции расчёта квадратного sqrt(…)
      Время от времени при расчёте вылетает ошибка «sqrt: DOMAIN error» (то есть, говоря по русски — аргумент sqrt <= 0) и программа вываливается.
      естественно, сначала при всех вызовах sqrt стал проверять , что аргумент > 0 .
      Не помогло, пошёл дальше . При ВСЕХ вызовах sqrt поставил конструкцию вида

      ExpandedWrap disabled

              if (diskr < 1E-30 || a == 0)

                MessageBox(NULL, «Задача не имеет решения», «Нет решения», MB_ICONINFORMATION);

              else

              {

                double x1, x2;

                try

                {

                  x1 = (-b+sqrt(diskr))/(2*a);

                  x2 = (-b-sqrt(diskr))/(2*a);

                }

                catch(…)

                {

                  MessageBox(NULL, «Ошибка sqrt в recalcModelBtnClick()», «Ошибка sqrt()», MB_ICONERROR);

                  x1 = x2 = -1.;

                }

                …….

              }

      Кое где помогло, стали выскакивать поименованные ошибки. Хотя не понимаю, почему вдруг могла появиться ошибка обработки? ведь проверял же на положительное значение. Ну это ладно ещё.
      Всё равно лезут время от времени ошибки «sqrt: DOMAIN error» несмотря на то, что без try нет ни одного вызова sqrt.

      Где искать грабли ? :wall:


      Swindler



      Сообщ.
      #2

      ,
      08.02.07, 10:53

        Шурик П., может _matherr поможет в определении ошибки?


        Denny



        Сообщ.
        #3

        ,
        08.02.07, 10:54

          Member

          **

          Рейтинг (т): 2

          MSDN: The sqrt function returns the square-root of x. If x is negative, sqrt returns an indefinite, by default.

          она возвращает ошибку, а не исключение генерит.


          Adil



          Сообщ.
          #4

          ,
          08.02.07, 11:56

            Я обычно делаю так

            ExpandedWrap disabled

              #include <math.h>

              static int matherr_id = -1;

              int _matherr( struct _exception *except )

              {

                if( matherr_id == 0 ) //our spy, no message

                {

                  matherr_id = except->type; //error flag (type of error)

                  return matherr_id; //no message (return != 0)

                }

                return 0;    // use the default actions

                //one line:

                //return ( matherr_id == 0 ) ? (matherr_id = except->type) : 0;

              }

                       // применительно к коду автора, юзать можно так

                        matherr_id = 0;

                        x1 = (-b+sqrt(diskr))/(2*a);

                        x2 = (-b-sqrt(diskr))/(2*a);

                        if( matherr_id != 0 )

                        {

                          //в matherr_id — тип ошибки (DOMAIN, SING, OVERFLOW и т.д.), можно вывести

                          MessageBox(NULL, «Ошибка sqrt в recalcModelBtnClick()», «Ошибка sqrt()», MB_ICONERROR);

                          x1 = x2 = -1.;

                        }

                        else

                          matherr_id = -1;


            Шурик П.



            Сообщ.
            #5

            ,
            08.02.07, 13:56

              Senior Member

              ****

              Рейтинг (т): 23

              Sorry всем и модераторам в том числе за тиражирование темы, что-то движок форума глючит. Пишет мне SQL ошибку создания темы, а тему тем не менее создаёт. Потому я и наплодил жуткое количество тем.

              Теперь по сути вопроса: просветите идиотика. Я был всю дорогу уверен, что конструкция
              try
              {
              Могущий вызвать сбой код
              }
              catch
              {
              Обработчик ошибок, в том числе и свой вывод сообщения об ошибке
              }

              — гарантировано подавит любое стандартное сообщение об ошибке и заменит его моим. Или я неправ?


              Adil



              Сообщ.
              #6

              ,
              08.02.07, 13:58

                Нет, это зависит от типа ошибки.


                Шурик П.



                Сообщ.
                #7

                ,
                08.02.07, 14:12

                  Senior Member

                  ****

                  Рейтинг (т): 23

                  Цитата Adil @ 08.02.07, 13:58

                  Нет, это зависит от типа ошибки.

                  Как понять — будет с помощью trycatch(…) подавлено стандартное сообщение или нет?

                  Adil
                  Конструкция с matherr, как я понимаю, вообще не блокирует исходное сообщение.
                  Просто позволяет на хвост ошибки повесить ещё и своё сообщение. Или блокирует?

                  Сообщение отредактировано: Шурик П. — 08.02.07, 14:28


                  Adil



                  Сообщ.
                  #8

                  ,
                  08.02.07, 16:07

                    Цитата Шурик П. @ 08.02.07, 14:12

                    Как понять — будет с помощью try … catch(…) подавлено стандартное сообщение или нет?

                    Повторяю — это зависит от типа ошибки. Как ты мог убедится на собственном примере — для мат ошибок сообщение об ошибке не «давится».

                    Цитата Шурик П. @ 08.02.07, 14:12

                    Или блокирует?

                    А справку почитать по _matherr — слабо? Или просто попробовать, если читать лень?

                    0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

                    0 пользователей:

                    • Предыдущая тема
                    • Borland C++ Builder/Turbo C++ Explorer
                    • Следующая тема

                    Рейтинг@Mail.ru

                    [ Script execution time: 0,0579 ]   [ 16 queries used ]   [ Generated: 10.02.23, 03:04 GMT ]  

                    ozx

                      Отправлено: 19.04.2005, 22:36

                    Ученик-кочегар

                    Группа: Участник
                    Сообщений: 9

                    Люди помогите пожалуйсто.
                    Есть такой код:

                    CODE
                     Q = b-L1*sin(FI);
                     P = a-L1*cos(FI);
                     F = (P*P+Q*Q+L2*L2-L3*L3)/(2*L2);

                     PSI = 2*atan((Q+sborka*sqrt(Q*Q+P*P-F*F))/(P+F));
                     KSI = acos((L2*cos(PSI)+L1*cos(FI)-a)/(L3));


                    Если выражение под корнем <0

                    то возникает ошибка программы с текстом:
                    SQRT: DOMAIN error,
                    а затем
                    ACOS: DOMAIN error.

                    Как можно подавить эти сообщения. Необходимо, что бы программа не обращала внимание на эти ошибки.

                    Георгий

                    Отправлено: 19.04.2005, 23:25

                    Почетный железнодорожник

                    Группа: Модератор
                    Сообщений: 874

                    пара try catch не помогает?
                    FataLL

                    Отправлено: 20.04.2005, 02:53

                    Дежурный стрелочник

                    Группа: Участник
                    Сообщений: 37

                    Блин, а просто

                    CODE
                    double dNum = …
                    if( dNum >= 0.0 )
                    {
                    sqrt…
                    }


                    не канает? Дожили… cool.gif

                    Отредактировано FataLL — 20/04/2005, 02:53

                    ozx

                    Отправлено: 20.04.2005, 09:51

                    Ученик-кочегар

                    Группа: Участник
                    Сообщений: 9

                    пробовал

                    CODE
                    try
                    {
                     sqrt…
                    }
                    catch(…)
                    {
                    }


                    Но все равно, ошибки возникают. Может я что-то ни то делаю.

                    А по-поводу второго варианта, это второе что мне пришло в голову, после try catch, Но я хочу понять, почему, ошибки не подавляются.

                    Возможно это из-за того что в блоке try я разместил много формул. Хотя я сомневаюсь.

                    FataLL

                    Отправлено: 21.04.2005, 11:40

                    Дежурный стрелочник

                    Группа: Участник
                    Сообщений: 37

                    Копни здесь попробуй:

                    CODE
                    #include <math.h>
                    #include <string.h>
                    #include <stdio.h>

                    int _matherr (struct _exception *a)
                    {
                    if (a->type == DOMAIN)
                    if (!strcmp(a->name,»sqrt»)) {
                    a->retval = sqrt (-(a->arg1));
                    return 1;
                    }
                    return 0;
                    }

                    int main(void)
                    {
                    double x = -2.0, y;
                    y = sqrt(x);
                    printf(«_Matherr corrected value: %lfn»,y);
                    return 0;
                    }

                    Все верно. try catch обрабатывает только функции Math.hpp, а там корня нет. Ты используешь sqrt, а его ошибка ловится _matherr. Там еще длинная версия есть, если чё…

                    Отредактировано FataLL — 21/04/2005, 11:51

                    ozx

                    Отправлено: 22.04.2005, 22:13

                    Ученик-кочегар

                    Группа: Участник
                    Сообщений: 9

                    Огромное спасибо FataLL. Ты мне очень помог.
                    Всё вроде как работает smile.gif

                    Понравилась статья? Поделить с друзьями:
                  • Sqlstate hy000 general error could not call class constructor
                  • Sqlstate hy000 general error 7 ssl syscall error eof detected
                  • Sqlstate hy000 general error 7 no connection to the server
                  • Sqlstate hy000 general error 2013 lost connection to mysql server during query
                  • Sqlstate hy000 general error 1205 lock wait timeout exceeded try restarting transaction