Pow overflow error c builder

Есть исходник программы:

Есть исходник программы:

ExpandedWrap disabled

    #include <iostream.h>

    #include <conio.h>

    #include <math.h>

    void main(void)

    {

     start:

      float x=5;

      int y=2;

      cout << «Vvedite 4islon»;

      cin >> x;

      cout << «Vvedite stepen’n»;

      cin >> y;

      cout << pow(x,y) << «n»;

      getch();

     goto start;

    }

Программа работает. Но есть один непонятный мне момент.

Компилирую в Borland C++ 3.1 командой bcc.
На выходе получаю exe’шник (если правильно понимаю 16-ти разрядный). Весит 51 Кб. Запускаю.
Хочу найти 308-ю степень числа 10… Выдаёт:

Хочу найти 309-ю степень числа 10… Выдаёт:

Цитата

pow OVERFLOW error
1,797693e+308

Здесь я так понимаю это ограничение представления чисел с плавающей запятой двойной точности 1.79 × 10^308
Затем компилирую с помощью CodeGear C++ Builder 2009 командой bcc32.
На выходе получаю exe’шник (Этот, я так понимаю, уже 32-ти разрядный). Весит 268 Кб. Запускаю.
Хочу найти 38-ю степень числа 10… Выдаёт:

Хочу найти 39-ю степень числа 10… Выдаёт 3 виндузятских message box’а (смотрите приложение внизу):

Цитата

XXX.exe — Ошибка приложения.
Исключение unknown software exception (0xc0000091) в приложении по адресу 0x0040132d…(Ну, там «ОК» — отладка приложения и т.д.)
Потом опять точно такую же ошибку…
И третий message box отличается только адресом:
***
… (0xc0000027) в приложении … 0x7c80df3c
***
И затем естественно приложение аварийно завершается…

Хочу найти 308-ю степень числа 10… Выдаёт то же аварийное завершение (см. чуть выше)…
Ну, а если я пытаюсь найти 309-ю степень то приложения уже не завершается аварийно. Выдаёт следующее сообщение:

Цитата

pow: OVERFLOW error
+INF

:wall:
Так в чём же фишка ??? Код ведь одинаковый. Значит дело в компиляторах ?
Связано ли это с 16 и 32 разрядностью (но почему то здесь по логике всё наоборот) ?
Или же это связанно с отличием в стандартах ? Разные типы данных в функции pow в зависимости от стандарта?
Может CodeGear намудрили ?
И почему тогда во втором случае программа аварийно завершается даже не объяснив в чём фишка, а в первом случае всё как по маслу и работает даже после переполнения ? :'(

Скомпилировал в QT (32-х разрядную). Всё работает. Только выдаёт сообщение «INF» когда выходит за 1,797693e+308… Здесь значит всё ОК…

Сообщение отредактировано: ToxaTheMan — 11.07.09, 16:15

Прикреплённая картинка

Прикреплённая картинка

AlexKreep

2 / 1 / 1

Регистрация: 23.11.2017

Сообщений: 100

1

21.11.2019, 18:44. Показов 1660. Ответов 3

Метки нет (Все метки)


Здравствуйте.
На форме использую два memo и button.
Программа, спустя несколько секунд после нажатия кнопки, выдаёт диалоговое окно с ошибкой. В чём дело?
Вот код:

C++
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
void __fastcall TForm2::Button1Click(TObject *Sender)
{
double a, s_x, h, y_x, x;
int b, n, fc;
 
a=0.1; b=1; n=80;
 
s_x=1-pow(x,2)/2;
y_x=0;
fc=1;
x=a;
h=(b-a)/10;
 
Memo1->Lines->Add("1: S("+FloatToStr(x)+")= "+FloatToStr(s_x));
for (int i = 2; i < n+1; i++) {
    for (int j = 2; j < (2*i)+1; i++) {
        fc=fc*j;
    }
    s_x=s_x+pow(-1,i)*pow(x,2*i)/fc;
    Memo1->Lines->Add(IntToStr(i)+": S("+FloatToStr(x)+")= "+FloatToStr(s_x));
 
    y_x=cos(x);
    Memo2->Lines->Add(IntToStr(i)+": Y("+FloatToStr(x)+")= "+FloatToStr(y_x));
 
    x=x+h;
    if (x>=1) continue;
}
}

Задача:
В заданиях с 1 по 15 (табл. 3.1) необходимо вывести на экран таблицу значений
функции Y(x) и ее разложения в ряд S(x) для x, изменяющегося от a до b с шагом
h=(b-a)/10. Близость значений S(x) и Y(x) во всем диапазоне значений x указывает
на правильность вычисления S(x) и Y(x).
Остальные условия в коде.

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Модератор

8255 / 5477 / 2249

Регистрация: 21.01.2014

Сообщений: 23,578

Записей в блоге: 3

22.11.2019, 10:31

2

Цитата
Сообщение от AlexKreep
Посмотреть сообщение

выдаёт диалоговое окно с ошибкой

А текст ошибки — он очень секретный? А то, может быть, поделились бы?



1



Супер-модератор

Эксперт Pascal/DelphiАвтор FAQ

32451 / 20945 / 8105

Регистрация: 22.10.2011

Сообщений: 36,213

Записей в блоге: 7

22.11.2019, 10:37

3

AlexKreep, в момент работы 8-ой строки у тебя переменная x еще не инициализирована, в ней мусор. Поэтому может быть все, что угодно.

Цитата
Сообщение от D1973
Посмотреть сообщение

А текст ошибки — он очень секретный?

Нет. Именно поэтому он записан в заголовке темы.



1



D1973

22.11.2019, 10:39


    Ошибка pow: OVERFLOW error

Не по теме:

Вот, блин, слона-то я и не заметил…



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

22.11.2019, 10:39

Выдает ошибку pow DOMAIN error
Доброго времени суток, выдает ошибку pow DOMAIN error при расчете примера. Всю голову сломал уже,…

Ошибки вычислений, POW: Domain Error
{float a,b,h,x,y,k;
a=StrToFloat(Edit1-&gt;Text);
b=StrToFloat(Edit2-&gt;Text);…

Ошибки Pow: Domain error и Log10: Domain error
Здравствуйте, возникла проблема, при компиляции программы выдаёт ошибки, указанные в заголовке,…

На другом компьютере exe файл C++ Builder 6 открывается,но выдает ошибку «pow : DOMAIN error»
На другом компьютере файл exe открывается но выдает ошибку: pow : DOMAIN error. На моем компе есть…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

4

Содержание

  1. pow: overflow error
  2. Повідомлення: 11
  3. 1 Тема від Betterthanyou 26.10.2015 17:45:33 Востаннє редагувалося Betterthanyou (26.10.2015 18:13:14)
  4. Тема: pow: overflow error
  5. 2 Відповідь від Master_Sergius 26.10.2015 18:16:38
  6. Re: pow: overflow error
  7. 3 Відповідь від Yola 26.10.2015 18:51:22 Востаннє редагувалося Yola (26.10.2015 18:51:59)
  8. Re: pow: overflow error
  9. 4 Відповідь від koala 26.10.2015 18:56:20 Востаннє редагувалося koala (26.10.2015 19:03:50)
  10. Re: pow: overflow error
  11. 5 Відповідь від Master_Sergius 26.10.2015 19:06:23
  12. Re: pow: overflow error
  13. 6 Відповідь від Betterthanyou 26.10.2015 21:25:49 Востаннє редагувалося Betterthanyou (26.10.2015 21:38:42)
  14. Re: pow: overflow error
  15. Thread: Catching an int overflow error
  16. Catching an int overflow error

pow: overflow error

Ласкаво просимо вас на україномовний форум з програмування, веб-дизайну, SEO та всього пов’язаного з інтернетом та комп’ютерами.

Будемо вдячні, якщо ви поділитись посиланням на Replace.org.ua на інших ресурсах.

Для того щоб створювати теми та надсилати повідомлення вам потрібно Зареєструватись.

Для відправлення відповіді ви повинні увійти або зареєструватися

Повідомлення: 11

1 Тема від Betterthanyou 26.10.2015 17:45:33 Востаннє редагувалося Betterthanyou (26.10.2015 18:13:14)

  • Betterthanyou
  • TEAM
  • Поза форумом
  • Звідки: Київ
  • Дата реєстрації: 16.05.2014
  • Повідомлень: 1 645Репутація: 986

Тема: pow: overflow error

Помилка pow: overflow error

Я хочу порахувати ануїтетні платежі для цього мені потрібно дізнатись коефіцієнт (формули брав звідси http://byhgalter.com/anuїtetnij-sposib- … igidnishe/)

9999999999 * ( 0,0825 * pow( (1 + 0,0825 ), 9999 ) / ( pow( (1 + 0,0825), 9999 ) -1 )
1,0825^9999 — і як це порахувати ?

2 Відповідь від Master_Sergius 26.10.2015 18:16:38

  • Master_Sergius
  • Користувач
  • Поза форумом
  • Дата реєстрації: 01.10.2014
  • Повідомлень: 1 068Репутація: 805

Re: pow: overflow error

Для с++ певно якісь ліби тра пошукати. Для python — numpy.
А взагалі, ви впевнені, шо у формулі все правильно? Бо там числа кілобайтні виходять, шо не є здорово для підрахунку якихось там платежів

3 Відповідь від Yola 26.10.2015 18:51:22 Востаннє редагувалося Yola (26.10.2015 18:51:59)

  • Yola
  • Replace Group
  • Поза форумом
  • Звідки: ukrainian.stackexchange.com
  • Дата реєстрації: 16.04.2013
  • Повідомлень: 839Репутація: 497

Re: pow: overflow error

Мовиться про кредит на 9999 місяців із відсотковою ставкою 9999999999 * 12 річних, я правильно зрозумів?

4 Відповідь від koala 26.10.2015 18:56:20 Востаннє редагувалося koala (26.10.2015 19:03:50)

  • koala
  • Лінива тваринка
  • На форумі
  • Дата реєстрації: 01.05.2013
  • Повідомлень: 14 353Репутація: 12212

Re: pow: overflow error

«Річні» у вас не зовсім річні, не буду казати, які саме.
Оцінімо ваше число:
Сума

2
1e10*2^1e4 = 1e10*10^3e3=1e310
Для MSVC long double — синонім double, верхня межа якого — 1e308. Заїхали за межі. Особливо з урахуванням того, що ви спершу обчислюєте великі числа, а потім їх ділите.
Як вибиратися?
— взяти інший компілятор (більшість використовує для long double 80-бітні чи більші, їх вистачить);
— взяти якусь бібліотеку для довгої арифметики, на кшталт boost::multiprecision (чи написати власну);
— дуже обережно обчислювати це число, розклавши pow на цикл — я завищував параметри, можливо, воно таки буде на межі;
— обчислювати не число, а його логарифм;
— пояснити нам, що саме ви хочете зробити і нащо, можливо, будуть інші способи.

5 Відповідь від Master_Sergius 26.10.2015 19:06:23

  • Master_Sergius
  • Користувач
  • Поза форумом
  • Дата реєстрації: 01.10.2014
  • Повідомлень: 1 068Репутація: 805

Re: pow: overflow error

До речі, якщо раптом ця формула виявиться правильною, то є один простий вихід. Значення буде наближене, але з дуже великою точністю.
Ось дивіться, якшо взяти за х оце ваше страшне pow( (1 + 0,0825), 9999 ), то тоді матимемо:

При таких великих значеннях х, одиницею можна знехтувати, відповідно, просто скоротити на х. Тоді матимете:

6 Відповідь від Betterthanyou 26.10.2015 21:25:49 Востаннє редагувалося Betterthanyou (26.10.2015 21:38:42)

  • Betterthanyou
  • TEAM
  • Поза форумом
  • Звідки: Київ
  • Дата реєстрації: 16.05.2014
  • Повідомлень: 1 645Репутація: 986

Re: pow: overflow error

А взагалі, ви впевнені, шо у формулі все правильно?

Так це коефіцієнт там і має виходити таке число

Мовиться про кредит на 9999 місяців із відсотковою ставкою 9999999999 * 12 річних, я правильно зрозумів?

майже так тільки річні 99%

— пояснити нам, що саме ви хочете зробити і нащо, можливо, будуть інші способи.

Ідея така якщо це значення обрахується правильно то всі решта будуть теж правильні так як програма приймає максимальне число для суми 10 цифр, для термін (місяців) 4, для річних (відсотків) 2

Источник

Thread: Catching an int overflow error

Thread Tools
Search Thread
Display

Catching an int overflow error

Hey everyone, I’ve got some code where I’m calculating a geometric mean:

Now sometimes the value of product gets too big for an integer, and I want to somehow catch this error when it happens. I could change it to a long, but I’d still want to catch the overflow error if it happened with a long, so the type of product doesn’t really matter to my question. (I can potentially get all sorts of crazy numbers in this code and I need to be able to deal with them all!)

I tried enclosing the code in a try/catch block like shown above, but when I stepped through the code with the debugger, it didn’t throw an exception. It just kept trying to multiply product (resulting in some very weird values for product). If product was an invalid entry for the pow function, then an exception was thrown at the pow function.

Any ideas on how I can catch or prevent this overflow error?

That is amazing — I changed it to a double and I never got that error (at least with the parameters I ran the program with). I guess a double can hold larger numbers than an int?

Still, I’m curious if anyone knows how to catch overflow errors like I mentioned in my first post, because that’s something that I’m sure other people may find useful as well!

In C++, there is no such thing as an overflow. If you keep looping with the for loop for( int i = 0; ; i++ ); the value of i would eventually become negative.

Naturally I didn’t feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! — Quzah

You. Fetch me my copy of the Wall Street Journal. You two, fight to the death — Stewie

Источник

  1. 11-04-2008


    #1

    skyt is offline


    Registered User


    pow: OVERFLOW error

    Hi, when i was running my excutable file, i got this error here is the power function i used to calculate the varible:

    Code:

    int i;
    			for(i = 1; i <= approximation; i++){
    				pi += pow(12, 0.5)*pow(-1, i+1)/((2*i - 1)*(pow(3, i-1)));
    			}

    any ideas?

    the error only occur when i pass a large number (over 1000) for approximation, and it runs for a few seconds and in the end it still will print out the correct answer, im just wondering should this be a big deal?

    Last edited by skyt; 11-04-2008 at 02:46 PM.

    Reason: more info


  2. 11-04-2008


    #2

    master5001 is offline


    Banned

    master5001's Avatar


    I would imagine an overflow took place. What value is approximation?


  3. 11-04-2008


    #3

    skyt is offline


    Registered User


    Quote Originally Posted by master5001
    View Post

    I would imagine an overflow took place. What value is approximation?

    when i enter 100 or 200 etc the error wouldnt occur, but when i use anything over 1000, it will occur.

    however, for the other method of mine,

    Code:

    int i;
    			for(i = 1; i <= approximation; i++){
    				pi += 4*pow(-1, i+1)/(2*i-1);
    			}

    i passed 40million for approximation and no such error occured


  4. 11-04-2008


    #4

    matsp is offline


    Kernel hacker


    I suspect that is caused by the fact that pow(3, n) is much more «growing» than pow(-1, n).

    Do you understand what «overflow» and «pow» actually do?


    Mats

    Compilers can produce warnings — make the compiler programmers happy: Use them!
    Please don’t PM me for help — and no, I don’t do help over instant messengers.


  5. 11-04-2008


    #5

    skyt is offline


    Registered User


    Quote Originally Posted by matsp
    View Post

    I suspect that is caused by the fact that pow(3, n) is much more «growing» than pow(-1, n).

    Do you understand what «overflow» and «pow» actually do?


    Mats

    yea, does it mean the numbers are getting too large for the memory to handle via the power function? is there anything i can do to fix it?


  6. 11-04-2008


    #6

    matsp is offline


    Kernel hacker


    Not for «memory to handle», but rather «for the math processing unit» — it is essentially the same as the E you get on a regular calculator if your result is too large (or you divide by zero or some such).

    There is really no easy solution to the problem, other than using a different method — on the other hand, I suspect by the time you are even CLOSE to overflow, the calculation isn’t making any changes to the result (because square root of 12 divided by 2 * i-1 * 3 to the power of i will be something like 1E-300 in the calculation leading up to the overflow, and with a double precision float, you only get about 15 or so digits precision, and PI is around 3, so to change the 15th decimal place, the number needs to be bigger than 1E-16 — so you have about 284 too many zeros at the beginnin of the number.

    Once your sqrt(12)/X calculation becomes smaller than about 1E-20, you can stop, because it’s not going to change the result. You can check it if you like, by printing the PI value and the sqrt(12)/X value in parallel. Once the number gets small enough, it’s not going to make any changes to PI at all — no matter how many times you do the calculation.


    Mats

    Compilers can produce warnings — make the compiler programmers happy: Use them!
    Please don’t PM me for help — and no, I don’t do help over instant messengers.


  7. 11-04-2008


    #7

    skyt is offline


    Registered User


    Quote Originally Posted by matsp
    View Post

    Not for «memory to handle», but rather «for the math processing unit» — it is essentially the same as the E you get on a regular calculator if your result is too large (or you divide by zero or some such).

    There is really no easy solution to the problem, other than using a different method — on the other hand, I suspect by the time you are even CLOSE to overflow, the calculation isn’t making any changes to the result (because square root of 12 divided by 2 * i-1 * 3 to the power of i will be something like 1E-300 in the calculation leading up to the overflow, and with a double precision float, you only get about 15 or so digits precision, and PI is around 3, so to change the 15th decimal place, the number needs to be bigger than 1E-16 — so you have about 284 too many zeros at the beginnin of the number.

    Once your sqrt(12)/X calculation becomes smaller than about 1E-20, you can stop, because it’s not going to change the result. You can check it if you like, by printing the PI value and the sqrt(12)/X value in parallel. Once the number gets small enough, it’s not going to make any changes to PI at all — no matter how many times you do the calculation.


    Mats

    that makes perfect sense, in the instruction i will just have to indicate that larger approximation will not help make pi more accurate when it gets too big. i really should have looked into the series itself before i post this problem, it’s purely a math problem rather than a programming problem. You are great!


  8. 11-05-2008


    #8

    matsp is offline


    Kernel hacker


    Quote Originally Posted by skyt
    View Post

    that makes perfect sense, in the instruction i will just have to indicate that larger approximation will not help make pi more accurate when it gets too big. i really should have looked into the series itself before i post this problem, it’s purely a math problem rather than a programming problem. You are great!

    No, if it was PURELY a math problem, then you have infinite (or relatively huge) precision. Computers limit the precision for the benefit of small size (a double takes up 8 bytes). You can get libraries (or write your own) that does «nearly infinite precission» math, e.g. GMP — limited only by available memory in the machine (or memory available to the process if the machine has HUGE amount of memory). You could quite easily use this to calculate several million digits of PI or some such — but of course, some others have been doing that already… :-)


    Mats

    Compilers can produce warnings — make the compiler programmers happy: Use them!
    Please don’t PM me for help — and no, I don’t do help over instant messengers.


IPB

> Внимание!

1. Пользуйтесь тегами кода. — [code][/code]
2. Точно указывайте язык, название и версию компилятора (интерпретатора).
3. Название темы должно быть информативным.
В описании темы указываем язык!!!

Наладить общение поможет, если вы подпишитесь по почте на новые темы в этом форуме.

> [С++ Builder 6] pow: domain error

сообщение 18.10.2009 20:03

Сообщение
#1


Профи
****

Группа: Пользователи
Сообщений: 920
Пол: Женский
Реальное имя: Марина

Репутация: -  2  +



Здравствуйте!

Столкнулась вот с такой проблемой:
В программе генерируются случайные числа, распределённые по нормальному з-ну. Но суть не совсем в этом.
Когда требуется сгенерировать 500-1000 значений — всё нормально, когда же я захотела получить 10 000 значений — ошибка pow: DOMAIN error..


double xi = 0, xiStar = 0, yi = 0;
float sigma1 = 1, sigma3 = 1;
float m1 = 5, m3 = 3;
..............
double GaussLow(int var)
{
randomize;
xi = static_cast<double>(rand()) / static_cast<double>(RAND_MAX);
xiStar = static_cast<double>(rand()) / static_cast<double>(RAND_MAX);
switch (var)
{
case 1:
yi = sigma1 * cos(2*M_PI*xi) * pow(-2*log10(xiStar),1/2) + m1;
break;
case 2:
yi = sigma3 * cos(2*M_PI*xi) * pow(-2*log10(xiStar),1/2) + m3;
}
return yi;
}
............
void __fastcall TForm2MS::ButGenClick(TObject *Sender)
{
double tempG = 0;
int test = 10000;
StrGrGen->RowCount = test+1;
StrGrGen->Visible = true;
StrGrGen->Cells[1][0] = "Íîðìàëüíûé ç-í";
StrGrGen->Cells[2][0] = "Íîðìàëüíûé ç-í";
for (int i=0;i<test;i++)
{
StrGrGen->Cells[0][i+1] = i+1;
tempG = GaussLow(1);
StrGrGen->Cells[1][i+1] = FloatToStrF(tempG,ffFixed,8,5);
tempG = 0;
tempG = GaussLow(2);
StrGrGen->Cells[2][i+1] = FloatToStrF(tempG,ffFixed,8,5);
}
}

Объясните пожалуйста, в чём тут дело? Как избежать ошибки..?
Подозреваю, что проблема можеть быть связана с областями определения (значения) pow или log10..

 Оффлайн  Профиль  PM 

 К началу страницы 

+ Ответить 

volvo

сообщение 18.10.2009 20:35

Сообщение
#2

Гость



Во-первых, randomize

()

… Во-вторых, этот самый randomize() в цикле запускать нельзя, только перед началом вычислений, однократно. В третьих, желательно переменную yi сделать ЛОКАЛЬНОЙ:

double xi = 0., xiStar = 0.;
double sigma1 = 1., sigma3 = 1.;
double m1 = 5., m3 = 3.;

double GaussLow(int var)
{
double yi; // Три
xi = static_cast<double>(rand()) / static_cast<double>(RAND_MAX);
xiStar = static_cast<double>(rand()) / static_cast<double>(RAND_MAX);
switch (var)
{
case 1:
yi = sigma1 * cos(2*M_PI*xi) * pow(-2*log10(xiStar),1/2) + m1;
break;
case 2:
yi = sigma3 * cos(2*M_PI*xi) * pow(-2*log10(xiStar),1/2) + m3;
}
return yi;
}
void __fastcall TForm2MS::ButGenClick(TObject *Sender)
{
// раз, два
randomize();

double tempG = 0;
int test = 10000;

StrGrGen->RowCount = test+1;
StrGrGen->Visible = true;
StrGrGen->Cells[1][0] = "Íîðìàëüíûé ç-í";
StrGrGen->Cells[2][0] = "Íîðìàëüíûé ç-í";
for (int i=0;i<test;i++)
{
StrGrGen->Cells[0][i+1] = i+1;
tempG = GaussLow(1);
StrGrGen->Cells[1][i+1] = FloatToStrF(tempG,ffFixed,8,5);
tempG = 0;
tempG = GaussLow(2);
StrGrGen->Cells[2][i+1] = FloatToStrF(tempG,ffFixed,8,5);
}
}

и куда делся domain error? smile.gif

 К началу страницы 

+ Ответить 

18192123

сообщение 18.10.2009 21:17

Сообщение
#3


Профи
****

Группа: Пользователи
Сообщений: 920
Пол: Женский
Реальное имя: Марина

Репутация: -  2  +



Цитата(volvo @ 18.10.2009 17:35) *

и куда делся domain error? smile.gif

я добавила ещё одну ф-ю EXpLow для генерации чисел, распределённых по экспоненциальному з-ну..
внесла изменения относительно randomize..
Запустила — отработало без ошибок!
Запустила снова — тут вам кроме pow: DOMAIN error, и log10: SING error, и pow: OVERFLOW error..

Вот как-то так.. blink.gif


//---------------------------------------------------------------------------

#include <vcl.h>
#include <math.h>
#pragma hdrstop

#include <utilcls.h>
#include <sysvari.h>
#include <ComObj.hpp>

#include "UnitMain.h"
#include "Unit_Stochastic_variables.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm2MS *Form2MS;

//my description
double xi = 0., xiStar = 0.;
double sigma1 = 1., sigma3 = 1.;
double m1 = 5., m3 = 3.;
double lambda2 = 0.16;
//---------------------------------------------------------------------------
__fastcall TForm2MS::TForm2MS(TComponent* Owner)
: TForm(Owner)
{

}
//---------------------------------------------------------------------------
double GaussLow(int var)
{
double yi;
xi = static_cast<double>(rand()) / static_cast<double>(RAND_MAX);
xiStar = static_cast<double>(rand()) / static_cast<double>(RAND_MAX);
switch (var)
{
case 1:
yi = sigma1 * cos(2*M_PI*xi) * pow(-2*log10(xiStar),1/2) + m1;
break;
case 2:
yi = sigma3 * cos(2*M_PI*xi) * pow(-2*log10(xiStar),1/2) + m3;
}
return yi;
}
//---------------------------------------------------------------------------
double ExpLow()
{
double yi;
xi = static_cast<double>(rand()) / static_cast<double>(RAND_MAX);
yi = (-1/lambda2) * log10(xi);
return yi;
}

void __fastcall TForm2MS::ButGenClick(TObject *Sender)
{
randomize();
double tempG = 0, tempE = 0;
int test = 10000;
StrGrGen->RowCount = test+1;
StrGrGen->Visible = true;
StrGrGen->Cells[1][0] = "Нормальный з-н";
StrGrGen->Cells[2][0] = "Нормальный з-н";
StrGrGen->Cells[3][0] = "Показательный з-н";
for (int i=0;i<test;i++)
{
StrGrGen->Cells[0][i+1] = i+1;
tempG = GaussLow(1);
StrGrGen->Cells[1][i+1] = FloatToStrF(tempG,ffFixed,8,5);
tempG = 0;
tempG = GaussLow(2);
StrGrGen->Cells[2][i+1] = FloatToStrF(tempG,ffFixed,8,5);
tempE = ExpLow();
StrGrGen->Cells[3][i+1] = FloatToStrF(tempE,ffFixed,8,5);
}
}

 Оффлайн  Профиль  PM 

 К началу страницы 

+ Ответить 

volvo

сообщение 18.10.2009 21:47

Сообщение
#4

Гость



case 1:
yi = sigma1 * cos(2*M_PI*xi) * pow(-2*log10(xiStar),1./2.) + m1; // <-- 1/2 в Сях = 0, тебе надо 1.0/2.0
break;
case 2:
yi = sigma3 * cos(2*M_PI*xi) * pow(-2*log10(xiStar),1./2.) + m3; // <-- Здесь - то же самое

Внимательнее с этими вещами…

 К началу страницы 

+ Ответить 

18192123

сообщение 20.10.2009 0:45

Сообщение
#5


Профи
****

Группа: Пользователи
Сообщений: 920
Пол: Женский
Реальное имя: Марина

Репутация: -  2  +



Ну просто напасть какая-то…Я снова увеличиваю размер генерируемой последовательности (до 60 000 элементов) — и вновь лезут ошибки log10:sign error… И в чём же теперь причина — для меня непостижимо(
Может рандом выдаёт какое-то недопустимое значение аргумента…?

Сообщение отредактировано: 18192123 — 20.10.2009 1:13

 Оффлайн  Профиль  PM 

 К началу страницы 

+ Ответить 

volvo

сообщение 20.10.2009 1:58

Сообщение
#6

Гость



Цитата

Может рандом выдаёт какое-то недопустимое значение аргумента…?

Вполне возможно… Я тебе даже скажу какое значение должно выдаваться, чтобы ты получала то, что получаешь: НОЛЬ… Если rand() вернул 0, то xiStar (естественно) тоже будет = 0, а это некорректные входные данные, это оговорено в описании функции. Так что придется тебе гарантировать, что аргумент log10 не будет нулевым. Ну, например, так:

int sure_rand()
{
int rnd = rand();

if(!rnd) rnd += 1;
return rnd;
}
...
xiStar = static_cast<double>(sure_rand()) / static_cast<double>(RAND_MAX);

Если сделать просто:

xiStar = static_cast<double>(rand() + 1) / static_cast<double>(RAND_MAX);

, то получишь сбой, когда rand() вернет RAND_MAX… Тогда xiStar примет значение > 1, следовательно log10(xiStar) станет больше 0, и ты попытаешься вычислить квадратный корень из отрицательного числа. Поверь, ни к чему хорошему это не приведет…

 К началу страницы 

+ Ответить 

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

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

500Gb HDD, 6Gb RAM, 2 Cores, 7 EUR в месяц — такие хостинги правда бывают

Связь с администрацией: bu_gen в домене octagram.name

Amateurtje

  • A
  • *
  • Newbie
  • Posts: 43
  • Logged

Hello,

I receive during compiling the error: Preprocessor.exe      Pow: Overflow error

it also started to give an error on one of my symbols: ‘symbol D’

I changed them all into ‘D_’.  now it compiles correctly, but the error is still there..
it leaves also the file a.lst which is about 500kb..

while i do not know how they normally look like (there is some asm inside), it is difficult for me to get info for the error from that file..

it is a small program and i use these symbols also in another program without problems..

anybody knows what this error means?



  • 1 person likes this.

Amateurtje

  • A
  • *
  • Newbie
  • Posts: 43
  • Logged

I did not find the time yet to break down my program. I hoped anybody could tell me a usual cause of this error to point me in the right direction.. I will use the coming evenings to break down the program…. It appeared while building but solving the errors that he gave at the same moment, did not solve the error… I will let you know what i find or if i have a code snippet i will post it here..

When it appeared, i was introducing a lot of new symbols, and scripts i have used in another program without errors…


I’m  away from my computer but fairly sure single letter identifiers are not permitted.
That is why you at least now have a compile.
The code snippet will help us help you when you have time to do that.
John

  • 1 person likes this.


Amateurtje

  • A
  • *
  • Newbie
  • Posts: 43
  • Logged

Unbtill now, in other programs, it went never wrong.. I used them to make digits on a 7-segment display. (the 7 1’s and 0′ represent a letter on the display).. Ofcourse, I can make them more letters but it reads nicer in the code when it is 1 letter.

I hope to have energy left this evening  ;D  ;D

thanks

  • 1 person likes this.


The preprocessor is a seperate program to the compiler and uses the computer’s capabilities for its floating point functions. So the Pow is trying to take the power of a value that is too large for it. Hence the overflow error.

Pow can produce extremely large values that are often larger than a compiler or floating point unit can handle.


Amateurtje

  • A
  • *
  • Newbie
  • Posts: 43
  • Logged

As far as I know I do not have a floating pont value (or it sees the symbols as floating points, but they are all byte values). As I understand, Pow is a function, isn’t it.. That, I do not use anywhere…

I have no clue where I use floating point variables in this script (no floats defined), but I will try to break the code down…


The preprocessor uses both integer and floating point for its «built in» expression functions, so even integer values will overflow if they are created too large. But the error indicates it is a floating point overflow.

I have no control over the limits of the C++ compiler’s built in functions that use the computer’s floating point hardware, so it will have limits. Now that 64-bit machines are dominant, I will get back into the preprocessor at some time and make it 64-bit compatible.

  • 3 people like this.


Amateurtje

  • A
  • *
  • Newbie
  • Posts: 43
  • Logged

Got it,

IT was the combination:

Symbol B = %00101100
And in the program:

Dig_4 = B 'Dig_4 is a byte variable
Solved by changing to:

Symbol B_ = %00101100
Dig_4 = B_

To be sure, I will change all single letter symbols to «X_»

Thanks for the help

  • 1 person likes this.


  • Proton BASIC Community

  • Proton (Positron)

  • Proton8 threads

  • Preprocessor.exe Pow: Overflow error

Понравилась статья? Поделить с друзьями:
  • Postgresql error 42p01 relation does not exist
  • Postgresql error 40001
  • Postgresql error 3d000
  • Postgresql error 28p01
  • Potplayer64 dll is modified or hacked ошибка