Search code examples
delphifloating-pointdelphi-7

How to handle floating point overflow?


I'm trying to do filtering .wav sample data value using the HAAR formula but got error "floating point overflow"

Edited : add more code

numsamples := round(wavehdr.SampleRate);
SetLength(wavedata[0].Data, numsamples);
Stream.Read(wavedata[0].Data[0], numsamples);
SetLength(cA1, numsamples);
SetLength(cD1, numsamples);
for i:=1 to numsamples-1 do begin 
cA1[i]:=(wavedata[0].Data[(i*2)-1]*0.7071) + (wavedata[0].Data[(i*2)]*0.7071);
cD1[i]:=(wavedata[0].Data[(i*2)-1]*0.7071) + (wavedata[0].Data[(i*2)]*-0.7071);
end;

where wavedata[0].Data[i], i get it from function Stream.Read to load sample data value of .wav file. I don't know why i got the error or what the error means and i've been searching the error mostly caused of divizion by zero, but there is no divizion by zero in my code. So maybe i could some help here what is the error mean in my code?

EDIT 1: (i'm really new to delphi, this code is not mine i found it internet. In my understanding the following code is the one to read .wav file sample data value)

type
  TWaveHeader = packed record

    Marker_RIFF: array [0..3] of char;
    ChunkSize: cardinal;


    Marker_WAVE: array [0..3] of char;


    Marker_fmt: array [0..3] of char;
    SubChunkSize: cardinal;


    FormatTag: word;

    { nChannels : 1  mono, 2  stereo }
    NumChannels: word;
    SampleRate: longint;
    BytesPerSecond: longint;
    BytesPerSample: word;
    BitsPerSample: word;


    Marker_data: array [0..3] of char;


    DataBytes: longint;
  end;

  TChannel = record

    Data : array of double;
  end;

And a private declaration :

private
    wavehdr:TWaveHeader;

the function :

FillChar(wavehdr, sizeof(wavehdr),0);
Stream.Read(wavehdr,sizeof(wavehdr));

i modified a bit of the code to handle null value while reading the sample data :

 if(IsNan(wavedata[0].Data[(i*2)-1])) then begin
      wavedata[0].Data[(i*2)-1]:=0;
    end
    else if(IsNan(wavedata[0].Data[(i*2)]))  then begin
      wavedata[0].Data[(i*2)]:=0;
    end;

Solution

  • for i:=0 ...

    (wavedata[0].Data[(i*2)-1]

    Do you really have array element Data[-1] ?

    P.S. Set range check compiler option while debugging.

    Edit: I see some new code, so let's go with step 2:

    SetLength(wavedata[0].Data, **numsamples**);
    
    for i:=1 to **numsamples**-1
    
    wavedata[0].Data[(**i*2)**]
    

    Have we to check thoroughly every line of code?