int main(void) { int i = 0,r = 0,tmp = 0,x,y,z,w,res; double tstart,tend; struct NUMBER a,b,c,d; struct timeval tv; gettimeofday(&tv,NULL); tstart= (double)tv.tv_sec + (double)tv.tv_usec * 1.e-6; setInt(&a,5); arctan(&a,&b); setInt(&a,16); multiple(&a,&b,&c); setInt(&a,239); arctan(&a,&b); setInt(&a,4); multiple(&a,&b,&d); sub(&c,&d,&a); printf("a= "); dispNumber(&a); putchar('\n'); gettimeofday(&tv,NULL); tend = (double)tv.tv_sec + (double)tv.tv_usec * 1.e-6; printf("所要時間 = %f秒\n",tend - tstart); return(0); }
void test() { int ndigit = 10000; /*位数可以自己试改,如:1000....*/ //10000位1秒,40000位16秒. /* if(argc == 2) ndigit = atoi(argv[1]); else { fprintf(stderr, "Usage: %s ndigit/n", argv[0]); fprintf(stderr, "(Assuming 10000 digits)/n"); } */ if (ndigit < 20) ndigit = 20; nblock = ndigit / 4; tot = (int *)malloc(nblock * sizeof(int)); t1 = (int *)malloc(nblock * sizeof(int)); t2 = (int *)malloc(nblock * sizeof(int)); t3 = (int *)malloc(nblock * sizeof(int)); if (!tot || !t1 || !t2 || !t3) { fprintf(stderr, "Not enough memory/n"); exit(1); } arctan(tot, t1, t2, 5, 1); mult(tot, 4); arctan(t3, t1, t2, 239, 2); sub(tot, t3); mult(tot, 4); print(tot); }
double calc(REC& a, REC& b, REC& c) { double ret=0.0; double ang_in, ang_out; double d, ang, deltaR, l, theta; ang = arctan(a.y - b.y, a.x - b.x); d = distance(a, b); deltaR = a.r - b.r; assert(d>1e-8); theta = asin(deltaR/d); ang_in = ang + theta + PI2/4.0; // normalize(ang_in); ang = arctan(c.y - b.y, c.x - b.x); d = distance(b, c); deltaR = c.r - b.r; theta = asin(deltaR/d); ang_out = ang - theta - PI2/4.0; if (ang_out<ang_in){ ang_out+=PI2; } assert(ang_out - ang_in < PI2+EPS); //impossible wrap around ret = b.r * (ang_out - ang_in); l = sqrt( d*d - deltaR*deltaR ); return ret+l; }
void find_conjugates(struct ado_setting *function) /*find_conjugates(void) the guy passed to this is the op or function portion of the act with the axis - function6-8 - already filled in. It fills in function3&4, with the time parameter theta = function5 set by whoever... */ { Short_xyz axis; SHORT rotate_op[9]; SHORT theta; zero_structure(rotate_op, 9*sizeof(SHORT) ); pj_copy_structure( &function->spin_axis, &axis, 3*sizeof(SHORT) ); theta = arctan( 0, SCALE_ONE) - arctan( axis.x, axis.y); while (theta > TWOPI/2 ) theta -= TWOPI; while (theta < -TWOPI/2) theta += TWOPI; rotate_op[5] = function->itheta1 = theta; act_rot_offset(&axis, rotate_op, SCALE_ONE); theta = arctan( 0, SCALE_ONE) - arctan( axis.y, axis.z); while (theta > TWOPI/2 ) theta -= TWOPI; while (theta < -TWOPI/2) theta += TWOPI; function->itheta2 = theta; }
float alfa(float x, float y) { float pi=3.14,aux; if(y<x) { aux=y/x; return arctan(aux); }else{ aux=(x/y); return pi/2-arctan(aux); } }
//create a new rectangle structure Rect* create_rect(CvPoint* ctr_pt, CvPoint* cls_pt, CvPoint* far_pt){ //compute center int32_t cnt_x = (cls_pt->x + far_pt->x )/2; int32_t cnt_y = (cls_pt->y + far_pt->y )/2; //compute area int smalld = sqrt(pow(cls_pt->x-ctr_pt->x,2)+pow(cls_pt->y-ctr_pt->y,2)); int larged = sqrt(pow(far_pt->x-ctr_pt->x,2)+pow(far_pt->y-ctr_pt->y,2)); int32_t area = smalld * larged; //compute angle int refx = (cls_pt->x + ctr_pt->x ) / 2; int refy = (cls_pt->y + ctr_pt->y ) / 2; refx -= cnt_x; refy -= cnt_y; int32_t theta = arctan(refx,refy); //create rectangle Rect* rect = (Rect*)calloc(1,sizeof(Rect)); rect->area = area; rect->c_x = cnt_x; rect->c_y = cnt_y; rect->theta = theta; return rect; }
void eval_arctan(void) { push(cadr(p1)); eval(); arctan(); }
double arctan2(double y, double x){ double ergebnis; ergebnis = 2.0 * arctan((y / (sqrt(x*x+y*y)+x)),30); return ergebnis; }
float alfa(float x, float y) { float pi=3.14,aux,radianos; if(x==0 && y==0) { return -1; } if(y<x) { aux=y/x; radianos=arctan(aux); }else{ aux=(x/y); radianos=pi/2-arctan(aux); } return (180*radianos)/pi; }
short orient() { short angle; angle = arctan(x,y); turnAngle(angle); rotateBasis(-angle); return angle; }
int main() { double t; t=arctan(5/7); printf("El arctan(5/7) es: \n"); scanf("%.5g",t); return 0; }
static int rub_spiral(void) { int itheta; int t0,t1,dt; int cenx, ceny; int lx,ly; char buf[40]; save_undo(); /* 1st get initial angle... */ if (!rub_line()) return(0); t0 = -arctan(x_1-x_0, y_1-y_0); itheta = t0+TWOPI/4; spi_ttheta = 0; for (;;) { spi_rad = calc_distance(x_0,y_0,grid_x,grid_y); t1 = -arctan(grid_x-x_0, grid_y-y_0); dt = t1-t0; if (dt > TWOPI/2) dt = dt-TWOPI; if (dt < -TWOPI/2) dt = dt+TWOPI; spi_ttheta += dt; t0 = t1; sprintf(buf, spiral_100 /* " %6ld degrees" */, spi_ttheta*360/TWOPI); top_text(buf); if (!make_spiral_poly(x_0,y_0,spi_rad,itheta,spi_ttheta)) return(0); dot_poly(&working_poly, sdot); wait_input(); dot_poly(&working_poly,copydot); if (PJSTDN || RJSTDN) break; } restore_top_bar(); return(PJSTDN); }
long long _main(long long argc, char *argv[]) { INDEXER x; time_t T1, T2; if (argc != 2) { puts("Syntax: ./prog2 <number> - <number> indicates the number of digits to compute\n"); exit(EXIT_FAILURE); } size = atol(argv[1]); if (size <= 0L) { puts("Invalid argument - need <number>\n"); exit(EXIT_FAILURE); } size = ((size + BASEDIGITS - 1) / BASEDIGITS) + 1; pi = malloc(sizeof(SHORT) * size); powers = malloc(sizeof(SHORT) * size); term = malloc(sizeof(SHORT) * size); if ((pi == NULL) || (powers == NULL) || (term == NULL)) { puts("Unable to allocate enough memory.\n"); exit(EXIT_FAILURE); } for (x = 0; x < size; x++) pi[x] = 0; T1 = time(NULL); #if defined ARC3 arctan(8, 3, 1); arctan(4, 7, 1); #elif defined ARC5 arctan(16, 5, 1); arctan(4, 70, -1); arctan(4, 99, 1); #elif defined ARC4 arctan(12, 4, 1); arctan(4, 20, 1); arctan(4, 1985, 1); #elif defined ARC10 arctan(32, 10, 1); arctan(4, 239, -1); arctan(16, 515, -1); #else /* Machin formula */ arctan(16, 5, 1); arctan(4, 239, -1); #endif T2 = time(NULL); Print(pi); #ifdef SHOWTIME puts("Calculation time "); PrintVal(T2-T1); puts(" cycles\n"); #endif return EXIT_SUCCESS; }
void Bullet::react(double dt){ this->x+=this->vx*dt; this->y+=this->vy*dt; this->rotateTo(arctan(this->vx,this->vy)); this->moveTo(this->x,this->y); }
int main(int argc, char *argv[]) { mp_result res; mpz_t sum1, sum2; int ndigits, out = 0; clock_t start, end; if (argc < 2) { fprintf(stderr, "Usage: %s <num-digits> [<radix>]\n", argv[0]); return 1; } if ((ndigits = abs(atoi(argv[1]))) == 0) { fprintf(stderr, "%s: you must request at least 1 digit\n", argv[0]); return 1; } else if ((mp_word)ndigits > MP_DIGIT_MAX) { fprintf(stderr, "%s: you may request at most %u digits\n", argv[0], (unsigned int)MP_DIGIT_MAX); return 1; } if (argc > 2) { int radix = atoi(argv[2]); if (radix < MP_MIN_RADIX || radix > MP_MAX_RADIX) { fprintf(stderr, "%s: you may only specify a radix between %d and %d\n", argv[0], MP_MIN_RADIX, MP_MAX_RADIX); return 1; } g_radix = radix; } mp_int_init(&sum1); mp_int_init(&sum2); start = clock(); /* sum1 = 16 * arctan(1/5) */ if ((res = arctan(g_radix, 16, 5, ndigits, &sum1)) != MP_OK) { fprintf(stderr, "%s: error computing arctan: %d\n", argv[0], res); out = 1; goto CLEANUP; } /* sum2 = 4 * arctan(1/239) */ if ((res = arctan(g_radix, 4, 239, ndigits, &sum2)) != MP_OK) { fprintf(stderr, "%s: error computing arctan: %d\n", argv[0], res); out = 1; goto CLEANUP; } /* pi = sum1 - sum2 */ if ((res = mp_int_sub(&sum1, &sum2, &sum1)) != MP_OK) { fprintf(stderr, "%s: error computing pi: %d\n", argv[0], res); out = 1; goto CLEANUP; } end = clock(); mp_int_to_string(&sum1, g_radix, g_buf, sizeof(g_buf)); printf("%c.%s\n", g_buf[0], g_buf + 1); fprintf(stderr, "Computation took %.2f sec.\n", (double)(end - start) / CLOCKS_PER_SEC); CLEANUP: mp_int_clear(&sum1); mp_int_clear(&sum2); return out; }
int main() { freopen("permetr.in", "r", stdin); freopen("permetr.out", "w", stdout); int N, i; scanf("%d", &N); // locate the starting point double ymin=1e50, xmin=1e50; int ori=-1; for (i=0; i<N; i++){ scanf("%lf %lf %lf", &list[i].x, &list[i].y, &list[i].r); if (list[i].y-list[i].r < ymin){ ymin = list[i].y - list[i].r; xmin = list[i].x; ori = i; } else if (list[i].y - list[i].r < ymin+EPS && list[i].x < xmin){ xmin = list[i].x; ori = i; } } int p; double last = -1.0; memset(flag, 0, sizeof(flag)); ptr[0] = ori; // printf("%.3lf %.3lf %.3lf\n", list[ori].x, list[ori].y, list[ori].r); for (p = 1; ; p++){ int sel = -1; double amin = 1.0e10, len = -1.0; double d, deltaR, ang, theta, l; //printf("%d\n", ptr[p-1]); for (i=0; i<N; i++){ if (ptr[p-1]==i) continue; ang = arctan(list[i].y - list[ptr[p-1]].y, list[i].x - list[ptr[p-1]].x); d = distance(list[i], list[ptr[p-1]]); deltaR = list[i].r - list[ptr[p-1]].r; assert(d>1e-8); if (d<1e-8){ printf("aoao\n"); } theta = asin(deltaR/d); ang -= theta; normalize(ang); l = sqrt( d*d - deltaR*deltaR ); if (ang<last){ ang += PI2; } if (ang < amin - EPS){ amin = ang; len = l; sel = i; } else if(ang < amin+EPS){ if (l > len){ len = l; sel = i; } } } assert(sel >= 0); last = amin; // printf("%.3lf %.3lf %.3lf\n", list[sel].x, list[sel].y, list[sel].r); ptr[p] = sel; if (flag[ptr[p-1]][ptr[p]]){ break; } flag[ptr[p-1]][ptr[p]] = 1; assert(p<2*MAXN-1);/// } N = p-1; assert(N>1); double acc; acc = calc(list[ptr[N-1]], list[ptr[0]], list[ptr[1]]); for (i=1; i<N; i++){ acc += calc(list[ptr[i-1]], list[ptr[i]], list[ptr[i+1]]); } printf("%.4e\n", acc); return 0; }
int match_X(IplImage* binary, CvPoint* points, int pixel_count, CvPoint* r_point, int cent_x, int cent_y, IplImage* debug){ int i,x,y; //useful variable names CvPoint* corners; //the corners of the image corners = (CvPoint*)calloc(4, sizeof(CvPoint)); corners[0].x = r_point->x; corners[0].y = r_point->y; //find the angle of the first corner x = corners[0].x - cent_x; y = corners[0].y - cent_y; int theta = arctan(y,x); //find the other 3 corners int maxr1 = 0; int maxr2 = 0; int maxr3 = 0; //keep track of the pixel sums on either side of angle0 int pxsum1 = 0; //this is bigger --> corner 0 goes in upper left int pxsum2 = 0; // this is bigger --> corner 0 goes in upper right for(i = pixel_count -1; i>=0; i--){ x = points[i].x - cent_x; y = points[i].y - cent_y; int tempang = arctan(y,x); //normalize angles if (tempang < theta) tempang += 360; //find tempr int tempr = (int)sqrt((double)(x*x + y*y)); if( tempang - theta > 315 ){ //we are in the same quadrant as the origional angle pxsum1++; } else if( tempang - theta > 225){ //call this quadrant 3 if( tempr > maxr3){ maxr3 = tempr; corners[3].x = points[i].x; corners[3].y = points[i].y; } } else if( tempang - theta > 135) { //call this quadrant 2 if( tempr > maxr2) { maxr2 = tempr; corners[2].x = points[i].x; corners[2].y = points[i].y; } } else if( tempang - theta > 45) { //call this quadrant 1 if( tempr > maxr1) { maxr1 = tempr; corners[1].x = points[i].x; corners[1].y = points[i].y; } } else { //we are again in the same quadrant as the origional angle pxsum2++; } #ifdef VISUAL_DEBUG_X //color every quadrant a different color if( tempang - theta > 315 ){ debug->imageData[3*points[i].y*debug->width+3*points[i].x+2]=0; debug->imageData[3*points[i].y*debug->width+3*points[i].x+1]=254; debug->imageData[3*points[i].y*debug->width+3*points[i].x+0]=254; } else if( tempang - theta > 225){ debug->imageData[3*points[i].y*debug->width+3*points[i].x+2]=254; debug->imageData[3*points[i].y*debug->width+3*points[i].x+1]=0; debug->imageData[3*points[i].y*debug->width+3*points[i].x+0]=0; } else if( tempang - theta > 135) { debug->imageData[3*points[i].y*debug->width+3*points[i].x+2]=0; debug->imageData[3*points[i].y*debug->width+3*points[i].x+1]=0; debug->imageData[3*points[i].y*debug->width+3*points[i].x+0]=254; } else if( tempang - theta > 45) { debug->imageData[3*points[i].y*debug->width+3*points[i].x+2]=254; debug->imageData[3*points[i].y*debug->width+3*points[i].x+1]=0; debug->imageData[3*points[i].y*debug->width+3*points[i].x+0]=254; } else { debug->imageData[3*points[i].y*debug->width+3*points[i].x+2]=0; debug->imageData[3*points[i].y*debug->width+3*points[i].x+1]=254; debug->imageData[3*points[i].y*debug->width+3*points[i].x+0]=0; } #endif } #ifdef VISUAL_DEBUG_X //draw a line between consecutive corners CvScalar boxcolor = {{0, 254, 0}}; cvLine(debug, corners[0], corners[1], boxcolor, 1, 8, 0); cvLine(debug, corners[1], corners[2], boxcolor, 1, 8, 0); cvLine(debug, corners[2], corners[3], boxcolor, 1, 8, 0); cvLine(debug, corners[3], corners[0], boxcolor, 1, 8, 0); //draw a circle at the center of the image CvPoint center = {cent_x, cent_y}; CvScalar centercolor = {{0, 0, 254}}; cvCircle(debug, center, 5, centercolor, 2, 8, 0); //mark corner 0 CvPoint corner0 = {corners[0].x, corners[0].y}; CvScalar cornercolor = {{254, 0, 254}}; cvCircle(debug, corner0, 5, cornercolor, 1, 8, 0); #endif //load template IplImage* xtemplate = cvLoadImage("../vision/xtemplate.png",CV_LOAD_IMAGE_GRAYSCALE); //get transformation matrix that would place corner values //in the correct location to compare to template //transform image //create an array for the 4 src points and dest points CvPoint2D32f* src; CvPoint2D32f* dst; src = (CvPoint2D32f*)calloc(4, sizeof(CvPoint2D32f)); dst = (CvPoint2D32f*)calloc(4, sizeof(CvPoint2D32f)); //populate the src array if( pxsum1 >= pxsum2 ){ for ( i=0; i<4; i++){ src[i].x = corners[i].x; src[i].y = corners[i].y; } }else{ for ( i=0; i<4; i++){ int j = i-1; if ( j<0 ) j = 3; src[i].x = corners[j].x; src[i].y = corners[j].y; } } //populate the dst array dst[0].x = 0; dst[0].y = 0; dst[1].x = 0; dst[1].y = 100; dst[2].x = 100; dst[2].y = 100; dst[3].x = 100; dst[3].y = 0; //get the transformation matrix CvMat* tmatrix = cvCreateMat(3,3,CV_32FC1); tmatrix = cvGetPerspectiveTransform( src, dst, tmatrix); //transform the image CvSize warpedsize = {100,100}; IplImage* warped = cvCreateImage(warpedsize, 8, 1); CvScalar fillcolor = {{0}}; cvWarpPerspective(binary, warped, tmatrix,CV_INTER_LINEAR+CV_WARP_FILL_OUTLIERS , fillcolor); #ifdef VISUAL_DEBUG_X IplImage* compared = cvCreateImage(cvGetSize(xtemplate),8,3); #endif //XOR the template image with our warped image int xor_sum = 0; for ( i=xtemplate->width*xtemplate->height -1; i>=0; i--){ int p1 = xtemplate->imageData[i]; int p2 = warped->imageData[i]; if(( p1 != 0 && p2 != 0 ) || ( p1 == 0 && p2 == 0 )){ xor_sum++; } #ifdef VISUAL_DEBUG_X if(p1 != 0 && p2 != 0){ compared->imageData[i*3+0] = 0x00; compared->imageData[i*3+1] = 0xff; compared->imageData[i*3+2] = 0x00; }else if(p1 == 0 && p2 == 0){ compared->imageData[i*3+0] = 0x00; compared->imageData[i*3+1] = 0xff; compared->imageData[i*3+2] = 0x00; }else if(p1 != 0){ compared->imageData[i*3+0] = 0xff; compared->imageData[i*3+1] = 0x00; compared->imageData[i*3+2] = 0x00; }else if(p2 != 0){ compared->imageData[i*3+0] = 0xff; compared->imageData[i*3+1] = 0x00; compared->imageData[i*3+2] = 0x00; } #endif } //compute confidence int confidence = xor_sum * 100 / (xtemplate->width*xtemplate->height); #ifdef VISUAL_DEBUG_X cvNamedWindow("Compared",CV_WINDOW_AUTOSIZE); cvShowImage("Compared", compared); cvNamedWindow("Warped", CV_WINDOW_AUTOSIZE); cvShowImage("Warped", warped); cvNamedWindow("Xtemplate", CV_WINDOW_AUTOSIZE); cvShowImage("Xtemplate",xtemplate); #endif //free memory cvReleaseImage(&xtemplate); cvReleaseImage(&warped); free(corners); free(src); free(dst); cvReleaseMat(&tmatrix); #ifdef VISUAL_DEBUG_X cvReleaseImage(&compared); #endif return confidence; }
int calculate_pi(int digits) { INDEXER x; time_t T1, T2; size = digits; size = ((size + BASEDIGITS - 1) / BASEDIGITS) + 1; pi = malloc(sizeof(SHORT) * size); powers = malloc(sizeof(SHORT) * size); term = malloc(sizeof(SHORT) * size); if ((pi == NULL) || (powers == NULL) || (term == NULL)) { return -1; } for (x = 0; x < size; x++) pi[x] = 0; #if defined ARC3 arctan(8, 3, 1); arctan(4, 7, 1); #elif defined ARC5 arctan(16, 5, 1); arctan(4, 70, -1); arctan(4, 99, 1); #elif defined ARC4 arctan(12, 4, 1); arctan(4, 20, 1); arctan(4, 1985, 1); #elif defined ARC10 arctan(32, 10, 1); arctan(4, 239, -1); arctan(16, 515, -1); #else /* Machin formula */ arctan(16, 5, 1); arctan(4, 239, -1); #endif Print(pi); return 0; }
void MainTask(void *arg) { ADI_AFE_DEV_HANDLE hDevice; int16_t dft_results[DFT_RESULTS_COUNT]; q15_t dft_results_q15[DFT_RESULTS_COUNT]; q31_t dft_results_q31[DFT_RESULTS_COUNT]; q31_t magnitude[DFT_RESULTS_COUNT / 2]; q15_t phase[DFT_RESULTS_COUNT / 2]; fixed32_t magnitude_result[DFT_RESULTS_COUNT / 2 - 1]; fixed32_t phase_result[DFT_RESULTS_COUNT / 2 - 1]; char msg[MSG_MAXLEN]; uint8_t err; done = 0; uint16_t pressure_analog; uint32_t pressure; nummeasurements = 0; uint32_t rtcCount; ADI_I2C_RESULT_TYPE i2cResult; // Initialize driver. rtc_Init(); // Calibrate. rtc_Calibrate(); // Initialize UART. if (uart_Init()) { FAIL("ADI_UART_SUCCESS"); } // Initialize I2C. i2c_Init(&i2cDevice); // Initialize flags. bRtcAlarmFlag = bRtcInterrupt = bWdtInterrupt = false; // Get the current count. if (adi_RTC_GetCount(hRTC, &rtcCount)) { FAIL("adi_RTC_GetCount failed"); } // Initialize the AFE API. if (adi_AFE_Init(&hDevice)) { FAIL("adi_AFE_Init"); } // AFE power up. if (adi_AFE_PowerUp(hDevice)) { FAIL("adi_AFE_PowerUp"); } // Excitation Channel Power-up. if (adi_AFE_ExciteChanPowerUp(hDevice)) { FAIL("adi_AFE_ExciteChanPowerUp"); } // TIA Channel Calibration. if (adi_AFE_TiaChanCal(hDevice)) { FAIL("adi_AFE_TiaChanCal"); } // Excitation Channel Calibration (Attenuation Enabled). if (adi_AFE_ExciteChanCalAtten(hDevice)) { FAIL("adi_AFE_ExciteChanCalAtten"); } // Update FCW in the sequence. seq_afe_acmeas2wire[3] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_FCW, FCW); // Update sine amplitude in the sequence. seq_afe_acmeas2wire[4] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_AMPLITUDE, SINE_AMPLITUDE); // Recalculate CRC in software for the AC measurement, because we changed. // FCW and sine amplitude settings. adi_AFE_EnableSoftwareCRC(hDevice, true); // Perform the impedance measurement. if (adi_AFE_RunSequence(hDevice, seq_afe_acmeas2wire, (uint16_t *)dft_results, DFT_RESULTS_COUNT)) { FAIL("Impedance Measurement"); } // Set RTC alarm. printf("rtcCount: %d\r\n", rtcCount); if (ADI_RTC_SUCCESS != adi_RTC_SetAlarm(hRTC, rtcCount + 120)) { FAIL("adi_RTC_SetAlarm failed"); } // Enable RTC alarm. if (ADI_RTC_SUCCESS != adi_RTC_EnableAlarm(hRTC, true)) { FAIL("adi_RTC_EnableAlarm failed"); } // Read the initial impedance. q31_t magnitudecal; q15_t phasecal; convert_dft_results(dft_results, dft_results_q15, dft_results_q31); arm_cmplx_mag_q31(dft_results_q31, &magnitudecal, 2); phasecal = arctan(dft_results[1], dft_results[0]); printf("raw rcal data: %d, %d\r\n", dft_results[1], dft_results[0]); printf("rcal (magnitude, phase) = (%d, %d)\r\n", magnitudecal, phasecal); // Create the message queue for communicating between the ISR and this task. dft_queue = OSQCreate(&dft_queue_msg[0], DFT_QUEUE_SIZE); // Hook into the DFT interrupt. if (ADI_AFE_SUCCESS != adi_AFE_RegisterAfeCallback( hDevice, ADI_AFE_INT_GROUP_CAPTURE, AFE_DFT_Callback, BITM_AFE_AFE_ANALOG_CAPTURE_IEN_DFT_RESULT_READY_IEN)) { FAIL("adi_AFE_RegisterAfeCallback"); } if (ADI_AFE_SUCCESS != adi_AFE_ClearInterruptSource( hDevice, ADI_AFE_INT_GROUP_CAPTURE, BITM_AFE_AFE_ANALOG_CAPTURE_IEN_DFT_RESULT_READY_IEN)) { FAIL("adi_AFE_ClearInterruptSource (1)"); } packed32_t q_result; void *q_result_void; OS_Q_DATA q_data; uint16_t q_size; bool inflated = false; while (true) { // Wait for the user to press the button. printf("MainTask: waiting for button.\n"); OSSemPend(ux_button_semaphore, 0, &err); if (err != OS_ERR_NONE) { FAIL("OSSemPend: MainTask"); } // TODO: fix bug when pressing button multiple times. // Have the pump task inflate the cuff. printf("MainTask: button detected. Resuming pump task.\n"); err = OSTaskResume(TASK_PUMP_PRIO); if (err != OS_ERR_NONE) { FAIL("OSTaskResume: MainTask (1)"); } // Wait a bit. printf("MainTask: waiting a bit.\n"); err = OSTimeDlyHMSM(0, 0, 1, 0); if (err != OS_ERR_NONE) { FAIL("OSTimeDlyHMSM: MainTask (3)"); } // Enable the DFT interrupt. printf("MainTask: enabling DFT interrupt.\n"); if (ADI_AFE_SUCCESS != adi_AFE_EnableInterruptSource( hDevice, ADI_AFE_INT_GROUP_CAPTURE, BITM_AFE_AFE_ANALOG_CAPTURE_IEN_DFT_RESULT_READY_IEN, true)) { FAIL("adi_AFE_EnableInterruptSource"); } PRINT("START\r\n"); printf("START\r\n"); while (true) { // Wait on the queue to get DFT data from the ISR (~76 Hz). //printf("MainTask: pending on DFT queue.\n"); q_result_void = OSQPend(dft_queue, 0, &err); q_result.pointer = q_result_void; if (err != OS_ERR_NONE) { FAIL("OSQPend: dft_queue"); } OSQQuery(dft_queue, &q_data); q_size = q_data.OSNMsgs; // Right after we get this data, get the transducer's value from the // Arduino. //printf("MainTask: getting transducer value via I2C.\n"); i2cResult = adi_I2C_MasterReceive(i2cDevice, I2C_PUMP_SLAVE_ADDRESS, 0x0, ADI_I2C_8_BIT_DATA_ADDRESS_WIDTH, i2c_rx, 3, false); if (i2cResult != ADI_I2C_SUCCESS) { FAIL("adi_I2C_MasterReceive: get pressure from Arduino"); } // Get the analog pressure value from the Arduino. if (i2c_rx[0] == ARDUINO_PRESSURE_AVAILABLE || i2c_rx[0] == ARDUINO_STILL_INFLATING) { pressure_analog = i2c_rx[1] | (i2c_rx[2] << 8); } else { FAIL("Corrupted or unexpected data from Arduino."); } // Convert the analog value to mmHg. pressure = transducer_to_mmhg(pressure_analog); //printf("MainTask: got pressure value: %d mmHg.\n", pressure); // If the pressure is below the threshold, we're done; break the loop. if (inflated && pressure < LOWEST_PRESSURE_THRESHOLD_MMHG) { PRINT("END\r\n"); printf("END\r\n"); inflated = false; break; } else if (pressure > LOWEST_PRESSURE_THRESHOLD_MMHG * 1.1) { inflated = true; } // Convert DFT results to 1.15 and 1.31 formats. dft_results[0] = q_result.parts.magnitude; dft_results[1] = q_result.parts.phase; convert_dft_results(dft_results, dft_results_q15, dft_results_q31); // Compute the magnitude using CMSIS. arm_cmplx_mag_q31(dft_results_q31, magnitude, DFT_RESULTS_COUNT / 2); // Calculate final magnitude values, calibrated with RCAL. fixed32_t magnituderesult; magnituderesult = calculate_magnitude(magnitudecal, magnitude[0]); q15_t phaseresult; phaseresult = arctan(dft_results[1], dft_results[0]); fixed32_t phasecalibrated; // Calibrate with phase from rcal. phasecalibrated = calculate_phase(phasecal, phaseresult); // TODO: dispatch to another thread? //printf("MainTask: sending data via UART.\n");; print_PressureMagnitudePhase("", pressure, magnituderesult, phasecalibrated, q_size); nummeasurements++; } // We're done measuring, for now. Disable the DFT interrupts. printf("MainTask: disabling DFT interrupts.\n"); if (ADI_AFE_SUCCESS != adi_AFE_EnableInterruptSource( hDevice, ADI_AFE_INT_GROUP_CAPTURE, BITM_AFE_AFE_ANALOG_CAPTURE_IEN_DFT_RESULT_READY_IEN, false)) { FAIL("adi_AFE_EnableInterruptSource (false)"); } // Tell the pump task to deflate the cuff. printf("MainTask: resuming pump task to deflate the cuff.\n"); err = OSTaskResume(TASK_PUMP_PRIO); if (err != OS_ERR_NONE) { FAIL("OSTaskResume: MainTask (2)"); } // Suspend until the pump finishes deflating. We can then go back to // listening for the user input. printf("MainTask: suspending to wait for pump task.\n"); err = OSTaskSuspend(OS_PRIO_SELF); if (err != OS_ERR_NONE) { FAIL("OSTaskSuspend: MainTask (3)"); } // Tell the UX that we're done for now. UX_Disengage(); } }
int main( int argc, char *argv[] ) { /* *************************************************************************** COMMAND LINE ARGUMENTS *************************************************************************** */ int eps = 54; // Number of bits of absolute precision desired // default to 54 bits (= machine double precision) int DOsqrt = 1; // a flag: defaults to 1 // (i.e., compute sqrt) int DOvalidate = 1; // a flag to validate Pi: defaults to 1 // (i.e., validate to 250 digits) if (argc > 1) eps = atoi(argv[1]); if (argc > 2) DOsqrt = atoi(argv[2]); if (argc > 3) { DOvalidate = atoi(argv[3]); if ((DOvalidate < 0) || (DOvalidate >2)) { std::cout << " !! Third argument in error, defaults to 1\n"; DOvalidate = 1; }; }; std::cout << "DOsqrt = " << DOsqrt << "; DOvalidate = " << DOvalidate << std::endl; /* *************************************************************************** COMPUTING Pi *************************************************************************** */ // Translates eps (in bits) to outputPrec (in digits) int outputPrec; // desired precision in digits outputPrec = (int) (eps * log(2.0)/log(10.0)); std::cout << " Output precision is " << outputPrec << " digits \n"; // Computing Auxilliary Values double t1 = arctan(5, eps + 6); // debugging output: // std::cout << std::setprecision(outputPrec+1) << "arctan(1/5) = " << t1 << std::endl; double t2 = arctan(239, eps + 4); // debugging output: // std::cout << std::setprecision(outputPrec+1) << "arctan(1/239) = " << t2 << std::endl; double pi = (4 * t1 - t2) * 4; pi.approx(CORE_posInfty, eps); // Output of Pi std::cout << " Pi = " << std::setprecision(outputPrec+1) << pi << std::endl; // Note: setprecision in C++ is actually "width" (=number of characters // in output. So we use "outputPrec + 1" to account for the decimal point. /* *************************************************************************** AUTOMATIC CHECK that (1) our internal value of Pi (2) our output value of Pi are both correct to 250 (or 2000) digits *************************************************************************** */ // Reading in digits of Pi from Files int prec = 0; // bit precision for the comparison std::ifstream from; // input stream from file if (DOvalidate == 0) { // no validation prec = 1; } if (DOvalidate == 1) { prec = core_min(eps, 830); // 830 bits = 250 digits. from.open("inputs/PI250", std::ios::in); // read 250 digits of Pi from file } if (DOvalidate == 2) { prec = core_min(eps, 6644); // 6644 bits = 2000 digits from.open("inputs/PI2000", std::ios::in); // read 2000 digits of Pi from file } if (DOvalidate > 0) { // validation needed std::string piStr; char c; while (from.get(c)) if ((c >= '0' && c <= '9') || (c=='.')) piStr += c; if (!from.eof()) std::cout << "!! Error in reading from PI250 \n"; from.close(); double bigPi(piStr.c_str()); // bigPi is the value of Pi from file // debug: // std::cout << " bigPi = " << std::setprecision(outputPrec + 1) << bigPi << std::endl; // CHECKING OUTPUT VALUE OF Pi: std::ostringstream ost; ost << std::setprecision(outputPrec+1) << pi << std::endl; piStr = ost.str(); // Need to take the min of outputPrec and the number of digits in bigPi int minPrec = 0; if (DOvalidate == 1) minPrec = core_min(outputPrec, 250); if (DOvalidate == 2) minPrec = core_min(outputPrec, 2000); double ee = pow(Expr(10), -minPrec+4); ee.approx(eps); std::cout << "pow(Expr(10), -minPrec+4)) = " << std::setprecision(outputPrec) << ee << std::endl; if ( fabs(Expr(piStr.c_str()) - bigPi) <= pow(Expr(10), -minPrec+4)) std::cout << " >> Output value of Pi verified to "<< minPrec << " digits\n"; else std::cout << " !! Output value of Pi INCORRECT to " << minPrec << " digits! \n"; // CHECKING INTERNAL VALUE of Pi: if ( fabs(pi - bigPi) <= (Expr)BigFloat::exp2(- prec +1)) std::cout << " >> Internal value of Pi verified up to " << prec << " bits\n"; else std::cout << " !! Internal value of Pi INCORRECT to " << prec << " bits! \n"; }; /* *************************************************************************** COMPUTING THE SQUARE ROOT of Pi to (eps - 2) bits of absolute precision *************************************************************************** */ if (DOsqrt == 0) return 0; // do not compute sqrt(Pi) // Here is sqrt(Pi) to 100 digits from Knuth: Expr SQRTPI="1.772453850905516027298167483341145182797549456122387128213807789852911284591032181374950656738544665"; double sPi = sqrt(pi); sPi.approx(CORE_posInfty, eps + 2); std::cout << " sqrt(Pi) = " << std::setprecision(outputPrec-1) << sPi << std::endl; /* *************************************************************************** AUTOMATIC CHECK that the internal value of computed sqrt(Pi) is correct up to the first 100 digits. *************************************************************************** */ prec = core_min(eps-1, 332); // 332 bits == 100 digits double d3 = fabs(sPi - SQRTPI); double tmp = pow(Expr(10), -(int) (prec * log(2.0)/log(10.0)) ); if ( d3 <= tmp ) std::cout << " >> Internal value of sqrt(Pi) verified to " << prec << " bits\n"; else std::cout << " !! Internal value of sqrt(Pi) INCORRECT to " << prec << " bits! \n"; return 0; }
void arctan(void) { double d; save(); p1 = pop(); if (car(p1) == symbol(TAN)) { push(cadr(p1)); restore(); return; } if (isdouble(p1)) { errno = 0; d = atan(p1->u.d); if (errno) stop("arctan function error"); push_double(d); restore(); return; } if (iszero(p1)) { push(zero); restore(); return; } if (isnegative(p1)) { push(p1); negate(); arctan(); negate(); restore(); return; } // arctan(sin(a) / cos(a)) ? if (find(p1, symbol(SIN)) && find(p1, symbol(COS))) { push(p1); numerator(); p2 = pop(); push(p1); denominator(); p3 = pop(); if (car(p2) == symbol(SIN) && car(p3) == symbol(COS) && equal(cadr(p2), cadr(p3))) { push(cadr(p2)); restore(); return; } } // arctan(1/sqrt(3)) -> pi/6 if (car(p1) == symbol(POWER) && equaln(cadr(p1), 3) && equalq(caddr(p1), -1, 2)) { push_rational(1, 6); push(symbol(PI)); multiply(); restore(); return; } // arctan(1) -> pi/4 if (equaln(p1, 1)) { push_rational(1, 4); push(symbol(PI)); multiply(); restore(); return; } // arctan(sqrt(3)) -> pi/3 if (car(p1) == symbol(POWER) && equaln(cadr(p1), 3) && equalq(caddr(p1), 1, 2)) { push_rational(1, 3); push(symbol(PI)); multiply(); restore(); return; } push_symbol(ARCTAN); push(p1); list(2); restore(); }
int main(void) { ADI_AFE_DEV_HANDLE hDevice; int16_t dft_results[DFT_RESULTS_COUNT]; q15_t dft_results_q15[DFT_RESULTS_COUNT]; q31_t dft_results_q31[DFT_RESULTS_COUNT]; q31_t magnitude[DFT_RESULTS_COUNT / 2]; q15_t phase[DFT_RESULTS_COUNT / 2]; fixed32_t magnitude_result[DFT_RESULTS_COUNT / 2 - 1]; fixed32_t phase_result[DFT_RESULTS_COUNT / 2 - 1]; char msg[MSG_MAXLEN]; uint32_t offset_code; uint32_t gain_code; uint32_t rtiaAndGain; /* Initialize system */ SystemInit(); /* Change the system clock source to HFXTAL and change clock frequency to 16MHz */ /* Requirement for AFE (ACLK) */ if (ADI_SYS_SUCCESS != SystemTransitionClocks(ADI_SYS_CLOCK_TRIGGER_MEASUREMENT_ON)) { FAIL("SystemTransitionClocks"); } /* SPLL with 32MHz used, need to divide by 2 */ SetSystemClockDivider(ADI_SYS_CLOCK_UART, 2); /* Test initialization */ test_Init(); /* Initialize static pinmuxing */ adi_initpinmux(); /* Initialize the UART for transferring measurement data out */ if (ADI_UART_SUCCESS != uart_Init()) { FAIL("uart_Init"); } /* Initialize the AFE API */ if (ADI_AFE_SUCCESS != adi_AFE_Init(&hDevice)) { FAIL("Init"); } /* Set RCAL and RTIA values */ if (ADI_AFE_SUCCESS != adi_AFE_SetRcal(hDevice, RCAL)) { FAIL("adi_AFE_SetRcal"); } if (ADI_AFE_SUCCESS != adi_AFE_SetRtia(hDevice, RTIA)) { FAIL("adi_AFE_SetTia"); } /* AFE power up */ if (ADI_AFE_SUCCESS != adi_AFE_PowerUp(hDevice)) { FAIL("adi_AFE_PowerUp"); } /* Delay to ensure Vbias is stable */ delay(2000000); /* Temp Channel Calibration */ if (ADI_AFE_SUCCESS != adi_AFE_TempSensChanCal(hDevice)) { FAIL("adi_AFE_TempSensChanCal"); } /* Auxiliary Channel Calibration */ if (ADI_AFE_SUCCESS != adi_AFE_AuxChanCal(hDevice)) { FAIL("adi_AFE_AuxChanCal"); } /* Excitation Channel Power-Up */ if (ADI_AFE_SUCCESS != adi_AFE_ExciteChanPowerUp(hDevice)) { FAIL("adi_AFE_ExciteChanPowerUp"); } /* TempCal results will be used to set the TIA calibration registers. These */ /* values will ensure the ratio between current and voltage is exactly 1.5 */ if (ADI_AFE_SUCCESS != adi_AFE_ReadCalibrationRegister(hDevice, ADI_AFE_CAL_REG_ADC_GAIN_TEMP_SENS, &gain_code)) { FAIL("adi_AFE_ReadCalibrationRegister, gain"); } if (ADI_AFE_SUCCESS != adi_AFE_WriteCalibrationRegister(hDevice, ADI_AFE_CAL_REG_ADC_GAIN_TIA, gain_code)) { FAIL("adi_AFE_WriteCalibrationRegister, gain"); } if (ADI_AFE_SUCCESS != adi_AFE_ReadCalibrationRegister(hDevice, ADI_AFE_CAL_REG_ADC_OFFSET_TEMP_SENS, &offset_code)) { FAIL("adi_AFE_ReadCalibrationRegister, offset"); } if (ADI_AFE_SUCCESS != adi_AFE_WriteCalibrationRegister(hDevice, ADI_AFE_CAL_REG_ADC_OFFSET_TIA, offset_code)) { FAIL("adi_AFE_WriteCalibrationRegister, offset"); } /* Update FCW in the sequence */ seq_afe_acmeasBioZ_4wire[3] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_FCW, FCW); /* Update sine amplitude in the sequence */ seq_afe_acmeasBioZ_4wire[4] = SEQ_MMR_WRITE(REG_AFE_AFE_WG_AMPLITUDE, SINE_AMPLITUDE); /* Recalculate CRC in software for the AC measurement, because we changed */ /* FCW and sine amplitude settings. */ adi_AFE_EnableSoftwareCRC(hDevice, true); while(true) { /* Perform the Impedance measurement */ if (ADI_AFE_SUCCESS != adi_AFE_RunSequence(hDevice, seq_afe_acmeasBioZ_4wire, (uint16_t *)dft_results, DFT_RESULTS_COUNT)) { FAIL("Impedance Measurement"); } /* Print DFT complex results to console */ PRINT("DFT results (real, imaginary):\r\n"); sprintf(msg, " CURRENT = (%6d, %6d)\r\n", dft_results[0], dft_results[1]); PRINT(msg); sprintf(msg, " VOLTAGE = (%6d, %6d)\r\n", dft_results[2], dft_results[3]); PRINT(msg); /* Convert DFT results to 1.15 and 1.31 formats. */ convert_dft_results(dft_results, dft_results_q15, dft_results_q31); /* Magnitude calculation */ /* Use CMSIS function */ arm_cmplx_mag_q31(dft_results_q31, magnitude, DFT_RESULTS_COUNT / 2); /* Calculate final magnitude value, calibrated with RTIA the gain of the instrumenation amplifier */ rtiaAndGain = (uint32_t)((RTIA * 1.5) / INST_AMP_GAIN); magnitude_result[0] = calculate_magnitude(magnitude[1], magnitude[0], rtiaAndGain); /* Phase calculations */ if (magnitude_result[0].full) { /* Current phase */ phase[0] = arctan(dft_results[1], dft_results[0]); /* Voltage phase */ phase[1] = arctan(dft_results[3], dft_results[2]); /* Impedance phase */ phase_result[0] = calculate_phase(phase[0], phase[1]); } /* No need to calculate the phase if magnitude is 0 (open circuit) */ else { /* Current phase */ phase[0] = 0; /* Voltage phase */ phase[1] = 0; /* Impedance phase */ phase_result[0].full = 0; } /* Print final results to console */ PRINT("Final results (magnitude, phase):\r\n"); print_MagnitudePhase("Impedance", magnitude_result[0], phase_result[0]); //sprintf_fixed32(tmp, magnitude); } /* Restore to using default CRC stored with the sequence */ adi_AFE_EnableSoftwareCRC(hDevice, false); /* AFE Power Down */ if (ADI_AFE_SUCCESS != adi_AFE_PowerDown(hDevice)) { FAIL("PowerDown"); } /* Uninitialize the AFE API */ if (ADI_AFE_SUCCESS != adi_AFE_UnInit(hDevice)) { FAIL("Uninit"); } /* Uninitilize the UART */ uart_UnInit(); PASS(); }
int main(int argc, char* argv[]) { std::vector<Mat<float> > mse; //Neural Networks settings : Topology topo; unsigned int nbrneurons = 25; unsigned int nbrlayer = 1; unsigned int nbrinput = width*height; unsigned int nbroutput = 10; //topo.push_back(nbrinput,NTNONE); //input layer topo.push_back(nbrinput,NTSIGMOID); //input layer //topo.push_back(nbrneurons, NTSIGMOID); topo.push_back(15, NTSIGMOID); //topo.push_back(nbroutput, NTSOFTMAX); //linear output topo.push_back(nbroutput, NTSIGMOID); //linear output NN<float> nn(topo); nn.learning = false; //------------------------------ //DATASET SETTINGS : report.open(report_fn.c_str(), ios::out); image.open(training_image_fn.c_str(), ios::in | ios::binary); // Binary image file label.open(training_label_fn.c_str(), ios::in | ios::binary ); // Binary label file // Reading file headers char number; for (int i = 1; i <= 16; ++i) { image.read(&number, sizeof(char)); } for (int i = 1; i <= 8; ++i) { label.read(&number, sizeof(char)); } //------------------------------ //checking rotation : Mat<float> im1(8,8, (char)1); Mat<float> im2( rotate(im1,PI/2.0f) ); im1.afficher(); im2.afficher(); //-------------------------------- //checking arctan !!! float y = -4.0f; float x = 4.0f; std::cout << arctan(y,x)*180.0f/(PI) << std::endl; //-------------------------------------------------- //checking reading : char labelval = 0; float theta = PI/2; im1 = inputMNIST(labelval); im2 = rotate(im1,theta); im2.afficher(); std::cout << "Rotation of : " << theta*180.0f/PI << std::endl; //--------------------------------------------------- int iteration = 25000; int offx = 2; int offy = 2; int size = 28; int countSuccess = 0; while( iteration) { Mat<float> rotatedinput( inputMNIST(labelval) ); //let us choose the rotation : float theta = ((float)(rand()%360))*PI/180.0f; //let us apply it : rotatedinput = extract( rotate(rotatedinput, theta), offx,offy, offx+(size-1), offy+(size-1) ); Mat<float> input( reshapeV( rotatedinput ) ); Mat<float> target( 0.0f, 10,1); target.set( 1.0f, labelval+1, 1); if(labelval < 9) { Mat<float> output( nn.feedForward( input) ); int idmax = idmin( (-1.0f)*output).get(1,1); transpose( operatorL(target,output) ).afficher(); std::cout << " LEARNING ITERATION : " << iteration << " ; IDMAX = " << idmax << std::endl; nn.backProp(target); //nn.backPropCrossEntropy(target); //counting : if(idmax == labelval+1) { countSuccess++; } //------------------- if( iteration % 1000 == 0) { std::cout << " TEST : " << countSuccess << " / " << 1000 << std::endl; mse.push_back(Mat<float>((float)countSuccess,1,1)); writeInFile(std::string("./mse.txt"), mse); countSuccess = 0; } iteration--; } } std::cout << " VALIDATION TEST : in progress.." << std::endl; iteration = 1000; int success = 0; while( iteration) { Mat<float> rotatedinput( inputMNIST(labelval) ); //let us choose the rotation : //float theta = rand()%360; float theta = ((float)(rand()%360))*PI/180.0f; //let us apply it : rotatedinput = extract( rotate(rotatedinput, theta), offx,offy, offx+(size-1), offy+(size-1) ); Mat<float> input( reshapeV( rotatedinput ) ); Mat<float> target( 0.0f, 10,1); target.set( 1.0f, labelval+1, 1); if(labelval < 5) { Mat<float> output( nn.feedForward( input)); int idmax = idmin( (-1.0f)*output).get(1,1); transpose(output).afficher(); std::cout << " ITERATION : " << iteration << " ; IDMAX = " << idmax << std::endl; if(idmax == labelval+1) { success++; } iteration--; } } std::cout << "VALIDATION TEST : " << success << " / 1000." << std::endl; report.close(); label.close(); image.close(); nn.save(std::string("neuralnetworksDIGITROTATED")); return 0; }
double arctan2(double y, double x){ double result; result = 2.0 * arctan((y / (sqrt(x*x+y*y)+x)),30); return result; }