float jk = 7700; float ck = 8000; - if i do int jk; I get rim=0;
printf (asin(jk/10500)) = 1.57897 - for example
printf (asin(ck/9500)) = 0.87868 - for example
float rim;
rim= asin(jk/10500)+ asin(ck/9500);
printf("\n%f", rim) = nan
Why i get nan?
I don't believe your "for example". Because I don't believe in magic. If you have two valid floats both pretty small, then their sum is not a nan. So, my guess is this:
either |jk| > 10500 or |ck| > 9500. So you make asin with an invalid ( > 1.0 or < -1.0) argument and thus get a nan.
Or you have made another error. Please post a compilable runnable example which will print NAN
There's either something wrong with your code or something seriously wrong with the iphone. The following code:
#include<stdio.h>
#include<math.h>
int main (void) {
printf ("%f\n", asin(1));
printf ("%f\n", asin(0.5));
float rim;
rim = asin(1) + asin (0.5);
printf ("%f\n", rim);
return 0;
}
produces a more sensible:
1.570796
0.523599
2.094395
In other words, both your asin(0.5) and your sum are incorrect.
Are you sure that you didn't actually do something like:
rim = asin(1 + asin (0.5));
That will indeed give you NaN.
Update based on your added info:
Your code still works fine in my environment:
#include<stdio.h>
#include<math.h>
int main (void) {
float jk = 7700;
//jk = 7700/10500;
jk = jk/10500;
printf ("%f\n", asin(jk));
float hg = 8000;
hg = hg / 9500;
printf ("%f\n", asin(hg));
float rim;
rim = asin(jk) + asin (hg);
printf ("%f\n", rim);
return 0;
}
outputting:
0.823212
1.001175
1.824387
You'll notice I changed jk = 7700/10500 to jk = jk/10500 since the latter gave you 0 due to the integer division, but I don't get NaN in either case. You really need to post a complete program which shows the errant behaviour.
#include <stdio.h>
#include <math.h>
main()
{
float jk=7700, ck=8000;
printf ("\n%f",asin(jk/10500));
printf ("\n%f",asin(ck/9500));
float rim;
rim= asin(jk/10500)+ asin(ck/9500);
printf("\n%f", rim);// = nan
}
Output
0.823212
1.001175
1.824387
I think your code is right. The problem is the value of jk and ck.
You kown if |jk/temp|>1 or |ck/temp|>1, the return of asin(jk/temp) will be nan.
so try to make |jk/temp|<=1 and |ck/temp| <=1, I believe that the return will be ok.
Related
I have double field ypos[] and in some cases instead of double is written into field -1.#INF00. I need to rewrite this values with 0.0, but i cant simply assign zero value, application falls everytime. Is there a way, how to solve this problem?
Please see http://codepad.org/KKYLhbkh for a simple example of how things "should work". Since you have not provided the code that doesn't work, we're guessing here.
#include <stdio.h>
#define INFINITY (1.0 / 0.0)
int main(void) {
double a[5] = {INFINITY, 1, 2, INFINITY, 4};
int ii;
for(ii = 0; ii < 5; ii++) {
printf("before: a[%d] is %lf\n", ii, a[ii]);
if(isinf(a[ii])) a[ii] = 0.0;
printf("after: a[%d] is %lf\n", ii, a[ii]);
}
return 0;
}
As was pointed out in #doynax 's comment, you might want to disable floating point exceptions to stop them from causing your program to keel over.
edit if your problem is caused by having taken a logarithm from a number outside of log's domain (i.e. log(x) with x<=0 ), the following code might help:
#include <stdio.h>
#include <signal.h>
#include <math.h>
#define INFINITY (1.0 / 0.0)
int main(void) {
double a[5] = {INFINITY, 1, 2, INFINITY, 4};
int ii;
signal(SIGFPE, SIG_IGN);
a[2] = log(-1.0);
for(ii = 0; ii < 5; ii++) {
printf("before: a[%d] is %lf\n", ii, a[ii]);
if(isinf(a[ii]) || isnan(a[ii])) a[ii] = 0.0;
printf("after: a[%d] is %lf\n", ii, a[ii]);
}
return 0;
}
You get a different value for log(0.0) (namely -Inf) and for log(-1.0) (namely nan). The above code shows how to deal with either of these.
A geuess that your problem is somewhere else. Can you write 0.0 before INF is written?
Sorry guys, I've solving this problem about 2 hours and tried to ask here but I've made a solution by comparing value of variable with -DBL_MAX. But thank you all for try.
I got some codes and I'm trying to fix some compiling bugs:
StkFrames& PRCRev :: tick( StkFrames& frames, unsigned int channel )
{
#if defined(_STK_DEBUG_)
if ( channel >= frames.channels() - 1 ) {
errorString_ << "PRCRev::tick(): channel and StkFrames arguments are incompatible!";
handleError( StkError::FUNCTION_ARGUMENT );
}
#endif
StkFloat *samples = &frames[channel];
unsigned int hop = frames.channels();
for ( unsigned int i=0; i<frames.frames(); i++, samples += hop ) {
*samples = tick( *samples );
*samples++; <<<<<<<<<--------- Expression result unused.
*samples = lastFrame_[1];
}
return frames;
}
I don't understand what the codes is trying to do. The codes are huge and I fixed quite a few. But googling didn't work for this.
Any ideas?
First, you do an increment (the line which actually gives you warning).
*samples++;
And then you assign to that variable something else, which makes previous action unused.
*samples = lastFrame_[1];
I recommend you to read this code inside 'for' loop more carefully. It doesn't look very logical.
I am developing an application in which I want to add echo effect in recorded audio files using objective-c.
I am using DIRAC to add other effect e.g. man to women, slow, fast.
now I have to make Robot voice of recorded voice. for robot voice I need to add echo effect
Please help me to do this
Echo is pretty simple. You need a delay line, and little multiplication. Assuming one channel and audio already represented in floating point, a delay line would look something like this (in C-like pseudo-code):
int LENGTH = samplerate * seconds; //seconds is the desired length of the delay in seconds
float buffer[ LENGTH ];
int readIndex = 0, writeIndex = LENGTH - 1;
float delayLine.readNext( float x ) {
float ret = buffer[readIndex];
++readIndex;
if( readIndex >= LENGTH )
readIndex = 0;
return ret;
}
void delayLine.writeNext( float x ) {
buffer[ writeIndex ] = x;
++writeIndex;
if( writeIndex >= LENGTH )
writeIndex = 0;
}
Don't forget to initialize the buffer to all zeros.
So that's your delay line. Basic usage would be this:
float singleDelay( float x ) {
delayLine.writeNext(x);
return delayLine.readNext( x );
}
But you won't hear much difference: it'll just come out later. If you want to hear a single echo, you'll need something like this:
float singleEcho( float x, float g ) {
delayLine.writeNext(x);
return x + g * delayLine.readNext( x );
}
where g is some constant, usually between zero and one.
Now say you want a stream of echos: "HELLO... Hello... hello... h..." like that. You just need to do a bit more work:
float echo( float x, float g ) {
float ret = x + g * delayLine.readNext( x );
delayLine.writeNext( ret );
return ret;
}
Notice how the output of the whole thing is getting fed back into the delay line this time, rather than the input. In this case, it's very important that |g| < 1.
You may run into issues of denormals here. I can't recall if that's an issue on iOS, but I don't think so.
I wrote the following C/MEX code using the FFTW library to control the number of threads used for a FFT computation from MATLAB. The code works great (complex FFT forward and backward) with the FFTW_ESTIMATE argument in the planner although it is slower than MATLAB. But, when I switch to the FFTW_MEASURE argument to tune up the FFTW planner, it turns out that applying one FFT forward and then one FFT backward does not return the initial image. Instead, the image is scaled by a factor. Using FFTW_PATIENT gives me an even worse result with null matrices.
My code is as follows:
Matlab functions:
FFT forward:
function Y = fftNmx(X,NumCPU)
if nargin < 2
NumCPU = maxNumCompThreads;
disp('Warning: Use the max maxNumCompThreads');
end
Y = FFTN_mx(X,NumCPU)./numel(X);
FFT backward:
function Y = ifftNmx(X,NumCPU)
if nargin < 2
NumCPU = maxNumCompThreads;
disp('Warning: Use the max maxNumCompThreads');
end
Y = iFFTN_mx(X,NumCPU);
Mex functions:
FFT forward:
# include <string.h>
# include <stdlib.h>
# include <stdio.h>
# include <mex.h>
# include <matrix.h>
# include <math.h>
# include </home/nicolas/Code/C/lib/include/fftw3.h>
char *Wisfile = NULL;
char *Wistemplate = "%s/.fftwis";
#define WISLEN 8
void set_wisfile(void)
{
char *home;
if (Wisfile) return;
home = getenv("HOME");
Wisfile = (char *)malloc(strlen(home) + WISLEN + 1);
sprintf(Wisfile, Wistemplate, home);
}
fftw_plan CreatePlan(int NumDims, int N[], double *XReal, double *XImag, double *YReal, double *YImag)
{
fftw_plan Plan;
fftw_iodim Dim[NumDims];
int k, NumEl;
FILE *wisdom;
for(k = 0, NumEl = 1; k < NumDims; k++)
{
Dim[NumDims - k - 1].n = N[k];
Dim[NumDims - k - 1].is = Dim[NumDims - k - 1].os = (k == 0) ? 1 : (N[k-1] * Dim[NumDims-k].is);
NumEl *= N[k];
}
/* Import the wisdom. */
set_wisfile();
wisdom = fopen(Wisfile, "r");
if (wisdom) {
fftw_import_wisdom_from_file(wisdom);
fclose(wisdom);
}
if(!(Plan = fftw_plan_guru_split_dft(NumDims, Dim, 0, NULL, XReal, XImag, YReal, YImag, FFTW_MEASURE *(or FFTW_ESTIMATE respectively)* )))
mexErrMsgTxt("FFTW3 failed to create plan.");
/* Save the wisdom. */
wisdom = fopen(Wisfile, "w");
if (wisdom) {
fftw_export_wisdom_to_file(wisdom);
fclose(wisdom);
}
return Plan;
}
void mexFunction( int nlhs, mxArray *plhs[],
int nrhs, const mxArray *prhs[] )
{
#define B_OUT plhs[0]
int k, numCPU, NumDims;
const mwSize *N;
double *pr, *pi, *pr2, *pi2;
static long MatLeng = 0;
fftw_iodim Dim[NumDims];
fftw_plan PlanForward;
int NumEl = 1;
int *N2;
if (nrhs != 2) {
mexErrMsgIdAndTxt( "MATLAB:FFT2mx:invalidNumInputs",
"Two input argument required.");
}
if (!mxIsDouble(prhs[0])) {
mexErrMsgIdAndTxt( "MATLAB:FFT2mx:invalidNumInputs",
"Array must be double");
}
numCPU = (int) mxGetScalar(prhs[1]);
if (numCPU > 8) {
mexErrMsgIdAndTxt( "MATLAB:FFT2mx:invalidNumInputs",
"NumOfThreads < 8 requested");
}
if (!mxIsComplex(prhs[0])) {
mexErrMsgIdAndTxt( "MATLAB:FFT2mx:invalidNumInputs",
"Array must be complex");
}
NumDims = mxGetNumberOfDimensions(prhs[0]);
N = mxGetDimensions(prhs[0]);
N2 = (int*) mxMalloc( sizeof(int) * NumDims);
for(k=0;k<NumDims;k++) {
NumEl *= NumEl * N[k];
N2[k] = N[k];
}
pr = (double *) mxGetPr(prhs[0]);
pi = (double *) mxGetPi(prhs[0]);
//B_OUT = mxCreateNumericArray(NumDims, N, mxDOUBLE_CLASS, mxCOMPLEX);
B_OUT = mxCreateNumericMatrix(0, 0, mxDOUBLE_CLASS, mxCOMPLEX);
mxSetDimensions(B_OUT , N, NumDims);
mxSetData(B_OUT , (double* ) mxMalloc( sizeof(double) * mxGetNumberOfElements(prhs[0]) ));
mxSetImagData(B_OUT , (double* ) mxMalloc( sizeof(double) * mxGetNumberOfElements(prhs[0]) ));
pr2 = (double* ) mxGetPr(B_OUT);
pi2 = (double* ) mxGetPi(B_OUT);
fftw_init_threads();
fftw_plan_with_nthreads(numCPU);
PlanForward = CreatePlan(NumDims, N2, pr, pi, pr2, pi2);
fftw_execute_split_dft(PlanForward, pr, pi, pr2, pi2);
fftw_destroy_plan(PlanForward);
fftw_cleanup_threads();
}
FFT backward:
This MEX function differs from the above only in switching pointers pr <-> pi, and pr2 <-> pi2 in the CreatePlan function and in the execution of the plan, as suggested in the FFTW documentation.
If I run
A = imread('cameraman.tif');
>> A = double(A) + i*double(A);
>> B = fftNmx(A,8);
>> C = ifftNmx(B,8);
>> figure,imagesc(real(C))
with the FFTW_MEASURE and FFTW_ESTIMATE arguments respectively I get this result.
I wonder if this is due to an error in my code or in the library. I tried different thing around the wisdom, saving not saving. Using the wisdom produce by the FFTW standalone tool to produce wisdom. I haven't seen any improvement. Can anyone suggest why this is happening?
Additional information:
I compile the MEX code using static libraries:
mex FFTN_Meas_mx.cpp /home/nicolas/Code/C/lib/lib/libfftw3.a /home/nicolas/Code/C/lib/lib/libfftw3_threads.a -lm
The FFTW library hasn't been compiled with:
./configure CFLAGS="-fPIC" --prefix=/home/nicolas/Code/C/lib --enable-sse2 --enable-threads --&& make && make install
I tried different flags without success. I am using MATLAB 2011b on a Linux 64-bit station (AMD opteron quad core).
FFTW computes not normalized transform, see here:
http://www.fftw.org/doc/What-FFTW-Really-Computes.html
Roughly speaking, when you perform direct transform followed by inverse one, you get
back the input (plus round-off errors) multiplied by the length of your data.
When you create a plan using flags other than FFTW_ESTIMATE, your input is overwritten:
http://www.fftw.org/doc/Planner-Flags.html
This is an interview question I saw on some site.
It was mentioned that the answer involves forming a recurrence of log2() as follows:
double log2(double x )
{
if ( x<=2 ) return 1;
if ( IsSqureNum(x) )
return log2(sqrt(x) ) * 2;
return log2( sqrt(x) ) * 2 + 1; // Why the plus one here.
}
as for the recurrence, clearly the +1 is wrong. Also, the base case is also erroneous.
Does anyone know a better answer?
How is log() and log10() actually implemented in C.
Perhaps I have found the exact answers the interviewers were looking for. From my part, I would say it's little bit difficult to derive this under interview pressure. The idea is, say you want to find log2(13), you can know that it lies between 3 to 4. Also 3 = log2(8) and 4 = log2(16),
from properties of logarithm, we know that log( sqrt( (8*16) ) = (log(8) + log(16))/2 = (3+4)/2 = 3.5
Now, sqrt(8*16) = 11.3137 and log2(11.3137) = 3.5. Since 11.3137<13, we know that our desired log2(13) would lie between 3.5 and 4 and we proceed to locate that. It is easy to notice that this has a Binary Search solution and we iterate up to a point when our value converges to the value whose log2() we wish to find. Code is given below:
double Log2(double val)
{
int lox,hix;
double rval, lval;
hix = 0;
while((1<<hix)<val)
hix++;
lox =hix-1;
lval = (1<<lox) ;
rval = (1<<hix);
double lo=lox,hi=hix;
// cout<<lox<<" "<<hix<<endl;
//cout<<lval<<" "<<rval;
while( fabs(lval-val)>1e-7)
{
double mid = (lo+hi)/2;
double midValue = sqrt(lval*rval);
if ( midValue > val)
{
hi = mid;
rval = midValue;
}
else{
lo=mid;
lval = midValue;
}
}
return lo;
}
It's been a long time since I've written pure C, so here it is in C++ (I think the only difference is the output function, so you should be able to follow it):
#include <iostream>
using namespace std;
const static double CUTOFF = 1e-10;
double log2_aux(double x, double power, double twoToTheMinusN, unsigned int accumulator) {
if (twoToTheMinusN < CUTOFF)
return accumulator * twoToTheMinusN * 2;
else {
int thisBit;
if (x > power) {
thisBit = 1;
x /= power;
}
else
thisBit = 0;
accumulator = (accumulator << 1) + thisBit;
return log2_aux(x, sqrt(power), twoToTheMinusN / 2.0, accumulator);
}
}
double mylog2(double x) {
if (x < 1)
return -mylog2(1.0/x);
else if (x == 1)
return 0;
else if (x > 2.0)
return mylog2(x / 2.0) + 1;
else
return log2_aux(x, 2.0, 1.0, 0);
}
int main() {
cout << "5 " << mylog2(5) << "\n";
cout << "1.25 " << mylog2(1.25) << "\n";
return 0;
}
The function 'mylog2' does some simple log trickery to get a related number which is between 1 and 2, then call log2_aux with that number.
The log2_aux more or less follows the algorithm that Scorpi0 linked to above. At each step, you get 1 bit of the result. When you have enough bits, stop.
If you can get a hold of a copy, the Feynman Lectures on Physics, number 23, starts off with a great explanation of logs and more or less how to do this conversion. Vastly superior to the Wikipedia article.