예제 #1
0
파일: main_str.c 프로젝트: matykiewicz/dsa
int FindMissingNumber(char *str, int len) {
  // note: it's easy to get rid of the logs but the code is just 
  // not understandable with all those counters
  for (int m = 1; m <= 6; ++m) {
    int n = GetVal(str, 0, m);
    if (n == -1) break;
    int missingNo = -1;
    int fail = 0;
    for (int i = m; i != len; i += 1 + log10l(n)) {
      if ((missingNo == -1) && (GetVal(str, i, 1 + log10l(n + 2)) == n + 2))
      {
	missingNo = n + 1;
	n+=2;
      }
      else if (GetVal(str, i, 1 + log10l(n + 1)) == n + 1)
      {
	n++;
      }
      else 
      {
	fail = 1;
	break;
      }
    }
    if (!fail) return missingNo; 
  }
  return -1; // not found or no missing number
}
예제 #2
0
int problem057(void)
{
	long double numer = 3, denom = 2; // 分子, 分母 

	int count = 0;
	for (int i = 1; i < 1000; ++i) {
		const long double tmp_numer = numer + denom * 2;
		const long double tmp_denom = numer + denom;
		numer = tmp_numer;
		denom = tmp_denom;
		if ((int)log10l(numer)+1 > (int)log10l(denom)+1)
			++count;
	}
	return count;
}
예제 #3
0
파일: exp_agent.c 프로젝트: levenkov/olver
static TACommandVerdict log10l_cmd(TAThread thread,TAInputStream stream)
{
    long double x, res;

    // Prepare

    x = readLongDouble(&stream);
    errno = 0;
    
    START_TARGET_OPERATION(thread);
    
    // Execute

    res = log10l(x);
    
    END_TARGET_OPERATION(thread);
    
    // Response
    
    writeLongDouble(thread, res);
    writeInt(thread, errno);

    sendResponse(thread);
    return taDefaultVerdict;
}
예제 #4
0
// constructor for the case without control
Pvalues::Pvalues(int length, int q_min, int q_max, int t_f, int t_r)
{
	has_control=false;
	n=2*q_max;
		
	// calculate probility of success for treatment
	// --------------------------------------------
	long double lambda_t = (q_max-q_min)*(t_r/(long double)length);
	long double rate_t   = (t_f/(long double)length)*(1-expl(-lambda_t));
	p_t = 1-exp(-rate_t*2);

	// init binomial distribution
	// --------------------------
	boost::math::binomial_distribution<long double> BinomialTreatment(n,p_t);

	// init p-values from n to 0
	// -------------------------
	long double pval=0;
	for(int k=n;0<=k;k--)
	{
		pval=pval+pdf(BinomialTreatment,(k));
		p_values[k]=pval;
		p_values_10log[k]=-log10l(pval);
	}
}
예제 #5
0
파일: funcion.cpp 프로젝트: DX94/freedfd
void
Log (Token ** Pila)
{
  Token *Operando = EntornoEjecucion_BuscaSimbolo (*Pila);
  if (Buzon.GetHuboError ())
    return;
  if (NoEsReal (Operando))
    {
      BorrarTokenSiEsVariable (Operando);
      return;
    }

  long double ValorDominio = Operando->GetDatoReal ();
  BorrarTokenSiEsVariable (Operando);
  long double ValorRetorno = log10l (ValorDominio);
  if (Buzon.GetHuboError ())
    return;
  Token *TokenRetorno = ConsigueToken (ValorRetorno);
  if (Buzon.GetHuboError ())
    return;
  delete Desapila (Pila);
  Apila (Pila, TokenRetorno);

  return;
}
예제 #6
0
codeWords generateHuffmanCodeWordsR_CW(int noOfCodeWords, bool firstCode)
{
	codeWords temp;

	int toplevel = (int) ((log10l(noOfCodeWords)/log10l(2)) + 1);
	int total = (int) (powl(2,(double)toplevel));

	int noOnPreLevel = total - noOfCodeWords;

	int codeWordCount = 0;

	recDownCodeWords(toplevel, noOfCodeWords - noOnPreLevel, noOfCodeWords, 0, codeWordCount, temp, *(new codeWord), false);

	return temp;

}
예제 #7
0
void test_log10()
{
    static_assert((std::is_same<decltype(log10((double)0)), double>::value), "");
    static_assert((std::is_same<decltype(log10f(0)), float>::value), "");
    static_assert((std::is_same<decltype(log10l(0)), long double>::value), "");
    assert(log10(1) == 0);
}
예제 #8
0
inline int floating_point_decimals(T t)
{
    BOOST_STATIC_ASSERT(boost::is_float<T>::value);
#if defined LMI_MSVCRT
    // COMPILER !! This C runtime not only writes infinity as "1.#INF"
    // instead of "inf" but also "respects" the precision specifier
    // when doing so, truncating it to "1." if this function were to
    // return zero.
    if(is_infinite(t))
        {
        return 4;
        }
#endif // defined LMI_MSVCRT
    // Avoid taking the logarithm of zero or infinity.
    if(0 == t || is_infinite(t))
        {
        return 0;
        }
// TODO ?? As this is written on 2005-11-03, cygwin lacks fabsl().
// It would be far better to write replacements for this and other
// such functions in one unit-tested module, and use them here as
// well as in 'round_to.hpp'.
#if !defined __CYGWIN__
    long double z = std::numeric_limits<T>::epsilon() * fabsl(t);
    return std::max(0, static_cast<int>(-log10l(z)));
#else  // defined __CYGWIN__
    long double z = std::numeric_limits<T>::epsilon() * t;
    if(t < 0.0)
        {
        z = -z;
        }
    return std::max(0, static_cast<int>(-log10(z)));
#endif // defined __CYGWIN__
}
예제 #9
0
long double complex
clog10l (long double complex z)
{
  long double complex v;

  COMPLEX_ASSIGN (v, log10l (cabsl (z)), cargl (z));
  return v;
}
예제 #10
0
    inline long double operator()(const long double& x) const 
    { 
#if defined(NTA_OS_WINDOWS)
      return log(x) / log(10.0);
#else
      return log10l(x); 
#endif
    }
예제 #11
0
int nth_digit (int n, int i) {
    int m = n;
    int j = log10l(n);
    while (j>i) {
        m /= 10;
        j--;
    }
    return m % 10;
}
예제 #12
0
long double TSolver::gcalc(const char f,const long double a,const long double b,const long double step) //calculates function
{
 #define ain(x) (a-step<=x && a+step>=x)
 #define bin(x) (b-step<=x && b+step>=x)
 #define angin(x) (torad(a)-step<x && torad(a)+step>x)
 switch (f)
   {case '+' : return a+b;
    case '-' : return a-b;
    case '*' : return a*b;
    case '/' : if (bin(0)) {Err=E_DEV_ZERO;return 0;};return a/b;
    case '!' : if (floorl(a)!=a) {Err=E_ARG;return 0;}return factor(a);
    case '_' : return -a;

    case cpi   : return M_PI;
    case cx    : return X;

    case fexp  : return exp(a);
    case fln   : if (a<0) {Err=E_ARG;return 0;}return logl(a);
    case flog  : if (a<0) {Err=E_ARG;return 0;}return log10l(a);
    case flogn : if (a<0) {Err=E_ARG;return 0;}return log(a)/log(b);

    case '^':
    case f_op_pow:
    case fpow  : if (a<0 && b<1 && b>0 && (!fmodl(b,2))) {Err=E_ARG;return 0;}return powl(a,b);
    case fsqr  : return a*a;
    case f_op_root:
    case froot : if (a<0 && (!fmodl(b,2))){Err=E_ARG;return 0;}
		   return (a>0 || (!fmodl(b,2)))?powl(a,1/b):-powl(-a,1/b);
    case fsqrt : if (a<0) {Err=E_ARG;return 0;}return sqrtl(a);
    case f_abs  : return fabsl(a);

    case fsin  : return sinl(a);
    case fcos  : return cosl(a);
    case ftan  : if (angin(M_PI_2) || angin(M_PI_2+M_PI)) {Err=E_ARG;return 0;} return tanl(a);
    case fctan : if (angin(0) || angin(M_PI)) {Err=E_ARG;return 0;} return 1/tanl(a);

    case fsin+ARC : if (fabsl(a)>1) {Err=E_ARG;return 0;} return asinl(a);
    case fcos+ARC : if (fabsl(a)>1) {Err=E_ARG;return 0;} return acosl(a);
    case ftan+ARC : return atanl(a);
    case fctan+ARC: return atanl(1/a);

    case fsin+HYP : return sinhl(a);
    case fcos+HYP : return coshl(a);
    case ftan+HYP : return tanhl(a);
    case fctan+HYP : return 1/tanhl(a);
#ifndef _OLD_
    case fsin+HYP+ARC : return asinhl(a);
    case fcos+HYP+ARC : return acoshl(a);
    case ftan+HYP+ARC : if (fabsl(a)>=1) {Err=E_ARG;return 0;} return atanhl(a);
    case fctan+HYP+ARC : if (angin(0)) {Err=E_ARG;return 0;} return atanhl(1/a);
#endif
    default: return 0;
   }
}
예제 #13
0
// constructor for the case treatment and control
Pvalues::Pvalues(int length, int q_min, int q_max, int t_f, int t_r, int c_f, int c_r)
{
	n=2*q_max;
	has_control=true;
	
	// calculate probility of success for treatment and control
	// --------------------------------------------------------
	
	long double lambda_t = (q_max-q_min) * (t_r/(long double)length);
	long double rate_t = (t_f/(long double)length) * (1-expl(-lambda_t));
	p_t = 1 - exp(-rate_t*2);
	
	long double lambda_c = (q_max-q_min) * (c_r/(long double)length);
	long double rate_c = (c_f/(long double)length) * (1-expl(-lambda_c));
	p_c = 1 - exp(-rate_c*2);
	
	// init binomial distribution
	// --------------------------
	
	boost::math::binomial_distribution<long double> BinomialTreatment(n,p_t);
	boost::math::binomial_distribution<long double> BinomialControl(n,p_c);	
	
	// init p-values from -n to n
	// --------------------------
	
	std::map<int, long double> DiffBinom;
	for(int d=-n;d<=n;d++)
	{
		for(int k=0;k<=(n-abs(d));k++)
		{
			if(0<=d)
			{
				DiffBinom[d]=DiffBinom[d]+pdf(BinomialTreatment,(k+abs(d)))*pdf(BinomialControl,k);
			}
			else
			{
				DiffBinom[d]=DiffBinom[d]+pdf(BinomialControl,k+abs(d))*pdf(BinomialTreatment,k);
			}
		}
	}
	
	long double pval=0;
	for(int d=n;d>=-n;d--)
	{
		pval=pval+DiffBinom[d];
		p_values[d]=pval;
		p_values_10log[d]=-log10l(pval);
	}
}
예제 #14
0
파일: main_str.c 프로젝트: matykiewicz/dsa
int FindMissingNum ( char *str, int len ) {
  
  int i = 0;
  int n = 0;
  int j = 0;
  int o = 0;
  int missingNo = -1;
  for ( i = 1; i <= 6; i++ ) {
    n = GetVal(str,0,i);
    printf("-%d",n); getchar();
    for ( j = i; j < len; j += 1 + i ) {
      o = GetVal(str,j,1+log10l(n+1));
      printf("+%d",o); getchar();
    }
  }
  return missingNo;

}
예제 #15
0
파일: eval.c 프로젝트: patmanteau/iclc
LONG_DOUBLE eval_expr_func(eval_context *ctx, ast_node *tree) {
    expr_func_data *func_data = (expr_func_data*)tree->data;
    if (strcmp(func_data->name, "sin") == 0) return sinl(eval_expr(ctx, func_data->rhs));
    else if (strcmp(func_data->name, "cos") == 0) return cosl(eval_expr(ctx, func_data->rhs));
    else if (strcmp(func_data->name, "tan") == 0) return tanl(eval_expr(ctx, func_data->rhs));
    else if (strcmp(func_data->name, "acos") == 0) return acosl(eval_expr(ctx, func_data->rhs));
    else if (strcmp(func_data->name, "asin") == 0) return asinl(eval_expr(ctx, func_data->rhs));
    else if (strcmp(func_data->name, "atan") == 0) return atanl(eval_expr(ctx, func_data->rhs));
    else if (strcmp(func_data->name, "cosh") == 0) return coshl(eval_expr(ctx, func_data->rhs));
    else if (strcmp(func_data->name, "sinh") == 0) return sinhl(eval_expr(ctx, func_data->rhs));
    else if (strcmp(func_data->name, "tanh") == 0) return tanhl(eval_expr(ctx, func_data->rhs));
    else if (strcmp(func_data->name, "log") == 0) return logl(eval_expr(ctx, func_data->rhs));
    else if (strcmp(func_data->name, "log10") == 0) return log10l(eval_expr(ctx, func_data->rhs));
    else if (strcmp(func_data->name, "ceil") == 0) return ceill(eval_expr(ctx, func_data->rhs));
    else if (strcmp(func_data->name, "fabs") == 0) return fabsl(eval_expr(ctx, func_data->rhs));
    else if (strcmp(func_data->name, "floor") == 0) return floorl(eval_expr(ctx, func_data->rhs));
    else if (strcmp(func_data->name, "sqrt") == 0) return sqrtl(eval_expr(ctx, func_data->rhs));
    else return eval_emit_error(ctx, "Unknown function %s.", func_data->name);
}
예제 #16
0
long double SigDig(long double x, size_t n)
{
    long double shift, result;

    if ((n == 0u) || (n > LDBL_DIG))
        result = x;
    else
    {
        --n;
        
#if defined(__DJGPP__) | defined(_MSC_VER)
        shift = pow(10.0L,(double)n - floor(log10(fabs(x))));
#else
        shift = powl(10.0L,(double)n - floorl(log10l(fabsl(x))));
#endif

        result = ToNearest(x * shift) / shift;
    }

    return result;
}
예제 #17
0
파일: __format.c 프로젝트: asegid/rhombus
static char *__format_double_int(long double value, int flags) {
	char *temp, *string;
	int expt;

	expt = log10l(value) + 1;
	value /= (int) powl(10, expt);

	temp = __format_double_frac(value, flags | FLAG_ALT | FLAG_MEXP, expt);

	if (value < 0) {
		string = strvcat("-", temp, NULL);
		free(temp);
	}
	else if (flags & FLAG_SIGN) {
		string = strvcat("+", temp, NULL);
		free(temp);
	}
	else {
		string = temp;
	}

	return string;
}
예제 #18
0
 inline long double MathTrait<long double>::log10( const long double val )
 {
   return log10l( val ) ;
 }
예제 #19
0
파일: afs.c 프로젝트: vytautas/afs
int main(int argc, char **argv)
{
	char **path;
	int opt;
	char verbose=0;
	char distrib=0;
	
	// handle arguments
	while ((opt = getopt(argc, argv, "+hvdV")) != -1)
		switch (opt)
		{
			case 'v':
				verbose=1;
				break;
			case 'd':
				distrib=1;
				break;
			case 'h':
				print_usage(argv[0]);
				return 0;
			case 'V':
				printf("Average File Size v%s \n", AFS_VERSION);
				return 0;
			default:
				print_usage(argv[0]);
				return 1;
		}
	if (optind >= argc)
	{
		print_usage(argv[0]);
		return 1;
	}
	else
	{
		path=(char **) malloc(sizeof(char *)*2);
		path[0]=argv[optind];
		path[1]=NULL;
	}

	if (verbose)
		printf("\nSize       File name\n");

	// start traversing
	FTS *ftsd;
	FTSENT *ent;
	struct stat64 s;
	TOTAL t;
	off64_t distr[DISTR_SIZE];
	char idx;
	MINMAX mm;

	mm.min=DISTR_SIZE;
	mm.max=0;
	bzero(&distr, sizeof(distr));
	t.files=t.bytes=0;
	ftsd = fts_open(path, FTS_PHYSICAL|FTS_NOSTAT|FTS_NOCHDIR, NULL);
	if (errno != 0)
	{
		perror("");
		return 1;
	}
	while ((ent = fts_read(ftsd)) != NULL)
		if (ent->fts_info == FTS_NSOK)
			if (lstat64(ent->fts_path, &s) == 0)
			{
				if (S_ISREG(s.st_mode))
				{
					if (verbose)
						printf("%10llu %s\n", s.st_size, ent->fts_path);
					t.bytes+=s.st_size;
					t.files++;

					//File size distribution
					if (distrib)
					{
						if (s.st_size > 0)
							idx=log10l(s.st_size)+1;
						else
							idx=0;
						distr[idx]++;
						if (mm.max < idx) mm.max=idx;
						if (mm.min > idx) mm.min=idx;
					}
				}
			}
			else
				perror(ent->fts_path);
	if (errno != 0)
	{
		perror("");
		return 1;
	}
	if (fts_close(ftsd) != 0) perror("FTS_CLOSE");

	// results
	printf("\nPath: %s\n", path[0]);
	printf("Total: %llu bytes, %llu files.\n", t.bytes, t.files);
	if (t.files>0)
		printf("Average: %llu\n", (t.bytes/t.files));
	free(path);

	if (distrib)
	{
		printf("File size distribution:\n");
		int i;
		for (i=mm.min; i<=mm.max; i++)
			printf("%10s: %4.1f%% (%llu files)\n", units[i], (float) (distr[i]*100)/t.files, distr[i]);
	}
	return 0;
}
예제 #20
0
void
domathl (void)
{
#ifndef NO_LONG_DOUBLE
  long double f1;
  long double f2;

  int i1;

  f1 = acosl(0.0);
  fprintf( stdout, "acosl          : %Lf\n", f1);

  f1 = acoshl(0.0);
  fprintf( stdout, "acoshl         : %Lf\n", f1);

  f1 = asinl(1.0);
  fprintf( stdout, "asinl          : %Lf\n", f1);

  f1 = asinhl(1.0);
  fprintf( stdout, "asinhl         : %Lf\n", f1);

  f1 = atanl(M_PI_4);
  fprintf( stdout, "atanl          : %Lf\n", f1);

  f1 = atan2l(2.3, 2.3);
  fprintf( stdout, "atan2l         : %Lf\n", f1);

  f1 = atanhl(1.0);
  fprintf( stdout, "atanhl         : %Lf\n", f1);

  f1 = cbrtl(27.0);
  fprintf( stdout, "cbrtl          : %Lf\n", f1);

  f1 = ceill(3.5);
  fprintf( stdout, "ceill          : %Lf\n", f1);

  f1 = copysignl(3.5, -2.5);
  fprintf( stdout, "copysignl      : %Lf\n", f1);

  f1 = cosl(M_PI_2);
  fprintf( stdout, "cosl           : %Lf\n", f1);

  f1 = coshl(M_PI_2);
  fprintf( stdout, "coshl          : %Lf\n", f1);

  f1 = erfl(42.0);
  fprintf( stdout, "erfl           : %Lf\n", f1);

  f1 = erfcl(42.0);
  fprintf( stdout, "erfcl          : %Lf\n", f1);

  f1 = expl(0.42);
  fprintf( stdout, "expl           : %Lf\n", f1);

  f1 = exp2l(0.42);
  fprintf( stdout, "exp2l          : %Lf\n", f1);

  f1 = expm1l(0.00042);
  fprintf( stdout, "expm1l         : %Lf\n", f1);

  f1 = fabsl(-1.123);
  fprintf( stdout, "fabsl          : %Lf\n", f1);

  f1 = fdiml(1.123, 2.123);
  fprintf( stdout, "fdiml          : %Lf\n", f1);

  f1 = floorl(0.5);
  fprintf( stdout, "floorl         : %Lf\n", f1);
  f1 = floorl(-0.5);
  fprintf( stdout, "floorl         : %Lf\n", f1);

  f1 = fmal(2.1, 2.2, 3.01);
  fprintf( stdout, "fmal           : %Lf\n", f1);

  f1 = fmaxl(-0.42, 0.42);
  fprintf( stdout, "fmaxl          : %Lf\n", f1);

  f1 = fminl(-0.42, 0.42);
  fprintf( stdout, "fminl          : %Lf\n", f1);

  f1 = fmodl(42.0, 3.0);
  fprintf( stdout, "fmodl          : %Lf\n", f1);

  /* no type-specific variant */
  i1 = fpclassify(1.0);
  fprintf( stdout, "fpclassify     : %d\n", i1);

  f1 = frexpl(42.0, &i1);
  fprintf( stdout, "frexpl         : %Lf\n", f1);

  f1 = hypotl(42.0, 42.0);
  fprintf( stdout, "hypotl         : %Lf\n", f1);

  i1 = ilogbl(42.0);
  fprintf( stdout, "ilogbl         : %d\n", i1);

  /* no type-specific variant */
  i1 = isfinite(3.0);
  fprintf( stdout, "isfinite       : %d\n", i1);

  /* no type-specific variant */
  i1 = isgreater(3.0, 3.1);
  fprintf( stdout, "isgreater      : %d\n", i1);

  /* no type-specific variant */
  i1 = isgreaterequal(3.0, 3.1);
  fprintf( stdout, "isgreaterequal : %d\n", i1);

  /* no type-specific variant */
  i1 = isinf(3.0);
  fprintf( stdout, "isinf          : %d\n", i1);

  /* no type-specific variant */
  i1 = isless(3.0, 3.1);
  fprintf( stdout, "isless         : %d\n", i1);

  /* no type-specific variant */
  i1 = islessequal(3.0, 3.1);
  fprintf( stdout, "islessequal    : %d\n", i1);

  /* no type-specific variant */
  i1 = islessgreater(3.0, 3.1);
  fprintf( stdout, "islessgreater  : %d\n", i1);

  /* no type-specific variant */
  i1 = isnan(0.0);
  fprintf( stdout, "isnan          : %d\n", i1);

  /* no type-specific variant */
  i1 = isnormal(3.0);
  fprintf( stdout, "isnormal       : %d\n", i1);

  /* no type-specific variant */
  f1 = isunordered(1.0, 2.0);
  fprintf( stdout, "isunordered    : %d\n", i1);

  f1 = j0l(1.2);
  fprintf( stdout, "j0l            : %Lf\n", f1);

  f1 = j1l(1.2);
  fprintf( stdout, "j1l            : %Lf\n", f1);

  f1 = jnl(2,1.2);
  fprintf( stdout, "jnl            : %Lf\n", f1);

  f1 = ldexpl(1.2,3);
  fprintf( stdout, "ldexpl         : %Lf\n", f1);

  f1 = lgammal(42.0);
  fprintf( stdout, "lgammal        : %Lf\n", f1);

  f1 = llrintl(-0.5);
  fprintf( stdout, "llrintl        : %Lf\n", f1);
  f1 = llrintl(0.5);
  fprintf( stdout, "llrintl        : %Lf\n", f1);

  f1 = llroundl(-0.5);
  fprintf( stdout, "lroundl        : %Lf\n", f1);
  f1 = llroundl(0.5);
  fprintf( stdout, "lroundl        : %Lf\n", f1);

  f1 = logl(42.0);
  fprintf( stdout, "logl           : %Lf\n", f1);

  f1 = log10l(42.0);
  fprintf( stdout, "log10l         : %Lf\n", f1);

  f1 = log1pl(42.0);
  fprintf( stdout, "log1pl         : %Lf\n", f1);

  f1 = log2l(42.0);
  fprintf( stdout, "log2l          : %Lf\n", f1);

  f1 = logbl(42.0);
  fprintf( stdout, "logbl          : %Lf\n", f1);

  f1 = lrintl(-0.5);
  fprintf( stdout, "lrintl         : %Lf\n", f1);
  f1 = lrintl(0.5);
  fprintf( stdout, "lrintl         : %Lf\n", f1);

  f1 = lroundl(-0.5);
  fprintf( stdout, "lroundl        : %Lf\n", f1);
  f1 = lroundl(0.5);
  fprintf( stdout, "lroundl        : %Lf\n", f1);

  f1 = modfl(42.0,&f2);
  fprintf( stdout, "lmodfl         : %Lf\n", f1);

  f1 = nanl("");
  fprintf( stdout, "nanl           : %Lf\n", f1);

  f1 = nearbyintl(1.5);
  fprintf( stdout, "nearbyintl     : %Lf\n", f1);

  f1 = nextafterl(1.5,2.0);
  fprintf( stdout, "nextafterl     : %Lf\n", f1);

  f1 = powl(3.01, 2.0);
  fprintf( stdout, "powl           : %Lf\n", f1);

  f1 = remainderl(3.01,2.0);
  fprintf( stdout, "remainderl     : %Lf\n", f1);

  f1 = remquol(29.0,3.0,&i1);
  fprintf( stdout, "remquol        : %Lf\n", f1);

  f1 = rintl(0.5);
  fprintf( stdout, "rintl          : %Lf\n", f1);
  f1 = rintl(-0.5);
  fprintf( stdout, "rintl          : %Lf\n", f1);

  f1 = roundl(0.5);
  fprintf( stdout, "roundl         : %Lf\n", f1);
  f1 = roundl(-0.5);
  fprintf( stdout, "roundl         : %Lf\n", f1);

  f1 = scalblnl(1.2,3);
  fprintf( stdout, "scalblnl       : %Lf\n", f1);

  f1 = scalbnl(1.2,3);
  fprintf( stdout, "scalbnl        : %Lf\n", f1);

  /* no type-specific variant */
  i1 = signbit(1.0);
  fprintf( stdout, "signbit        : %i\n", i1);

  f1 = sinl(M_PI_4);
  fprintf( stdout, "sinl           : %Lf\n", f1);

  f1 = sinhl(M_PI_4);
  fprintf( stdout, "sinhl          : %Lf\n", f1);

  f1 = sqrtl(9.0);
  fprintf( stdout, "sqrtl          : %Lf\n", f1);

  f1 = tanl(M_PI_4);
  fprintf( stdout, "tanl           : %Lf\n", f1);

  f1 = tanhl(M_PI_4);
  fprintf( stdout, "tanhl          : %Lf\n", f1);

  f1 = tgammal(2.1);
  fprintf( stdout, "tgammal        : %Lf\n", f1);

  f1 = truncl(3.5);
  fprintf( stdout, "truncl         : %Lf\n", f1);

  f1 = y0l(1.2);
  fprintf( stdout, "y0l            : %Lf\n", f1);

  f1 = y1l(1.2);
  fprintf( stdout, "y1l            : %Lf\n", f1);

  f1 = ynl(3,1.2);
  fprintf( stdout, "ynl            : %Lf\n", f1);
#endif
}
예제 #21
0
파일: __format.c 프로젝트: asegid/rhombus
static char *__format_double(long double value, int flags, int precision) {
	char *int_part;
	char *dec_part;
	char *string;
	long double i;

	if (isnan(value)) {
		if (flags & FLAG_UPPER) {
			return strdup("NAN");
		}
		else {
			return strdup("nan");
		}
	}

	if (isinf(value)) {
		if (flags & FLAG_UPPER) {
			if (value < 0) {
				return strdup("-INF");
			}
			else {
				if (flags & FLAG_SIGN) {
					return strdup("+INF");
				}
				else {
					return strdup("INF");
				}
			}
		}
		else {
			if (value < 0) {
				return strdup("-inf");
			}
			else {
				if (flags & FLAG_SIGN) {
					return strdup("+inf");
				}
				else {
					return strdup("inf");
				}
			}
		}
	}

	if (flags & FLAG_EXP || (flags & FLAG_MEXP && value > 1000000000)) {
		i = log10l(value);
		value /= powl(10, floorl(i));

		int_part = __format_double(value, flags & ~(FLAG_EXP), precision);
		dec_part = __format_int(i, flags | FLAG_SIGN);

		string = strvcat(int_part, (flags & FLAG_UPPER) ? "E" : "e", dec_part, NULL);

		free(int_part);
		free(dec_part);
	}
	else {
		value = modfl(value, &i);

		if (value > 2000000000) {
			int_part = __format_double_int(i, flags);
		}
		else {
			int_part = __format_int(i, flags);
		}
		dec_part = __format_double_frac(value, flags, precision);

		if (i == 0.0 && value < 0) {
			if (value != 0.0 || flags & FLAG_ALT) {
				string = strvcat("-", int_part, ".", dec_part, NULL);
			}
			else {
				string = strvcat("-", int_part, NULL);
			}
		}
		else {
			if (value != 0.0 || flags & FLAG_ALT) {
				string = strvcat(int_part, ".", dec_part, NULL);
			}
			else {
				string = strdup(int_part);
			}
		}

		free(int_part);
		free(dec_part);
	}

	return string;
}
예제 #22
0
static inline double lb(double x)
{
	return (double)(log10l((double)x)/log10l(2.0));
}
예제 #23
0
static int testl(long double long_double_x, int int_x, long long_x)
{
int r = 0;
r += __finitel(long_double_x);
r += __fpclassifyl(long_double_x);
r += __isinfl(long_double_x);
r += __isnanl(long_double_x);
r += __signbitl(long_double_x);
r += acoshl(long_double_x);
r += acosl(long_double_x);
r += asinhl(long_double_x);
r += asinl(long_double_x);
r += atan2l(long_double_x, long_double_x);
r += atanhl(long_double_x);
r += atanl(long_double_x);
r += cbrtl(long_double_x);
r += ceill(long_double_x);
r += copysignl(long_double_x, long_double_x);
r += coshl(long_double_x);
r += cosl(long_double_x);
r += erfcl(long_double_x);
r += erfl(long_double_x);
r += exp2l(long_double_x);
r += expl(long_double_x);
r += expm1l(long_double_x);
r += fabsl(long_double_x);
r += fdiml(long_double_x, long_double_x);
r += floorl(long_double_x);
r += fmal(long_double_x, long_double_x, long_double_x);
r += fmaxl(long_double_x, long_double_x);
r += fminl(long_double_x, long_double_x);
r += fmodl(long_double_x, long_double_x);
r += frexpl(long_double_x, &int_x);
r += hypotl(long_double_x, long_double_x);
r += ilogbl(long_double_x);
r += ldexpl(long_double_x, int_x);
r += lgammal(long_double_x);
r += llrintl(long_double_x);
r += llroundl(long_double_x);
r += log10l(long_double_x);
r += log1pl(long_double_x);
r += log2l(long_double_x);
r += logbl(long_double_x);
r += logl(long_double_x);
r += lrintl(long_double_x);
r += lroundl(long_double_x);
r += modfl(long_double_x, &long_double_x);
r += nearbyintl(long_double_x);
r += nextafterl(long_double_x, long_double_x);
r += nexttowardl(long_double_x, long_double_x);
r += powl(long_double_x, long_double_x);
r += remainderl(long_double_x, long_double_x);
r += remquol(long_double_x, long_double_x, &int_x);
r += rintl(long_double_x);
r += roundl(long_double_x);
r += scalblnl(long_double_x, long_x);
r += scalbnl(long_double_x, int_x);
r += sinhl(long_double_x);
r += sinl(long_double_x);
r += sqrtl(long_double_x);
r += tanhl(long_double_x);
r += tanl(long_double_x);
r += tgammal(long_double_x);
r += truncl(long_double_x);
return r;
}
예제 #24
0
int LL1Parsing::GetLength(long long int code)
{
	return ((int)log10l(code) + 1);
}
예제 #25
0
TEST(math, log10l) {
  ASSERT_FLOAT_EQ(3.0, log10l(1000.0));
}
예제 #26
0
static void
output_float (st_parameter_dt *dtp, const fnode *f, GFC_REAL_LARGEST value)
{
#if defined(HAVE_GFC_REAL_16) && __LDBL_DIG__ > 18
# define MIN_FIELD_WIDTH 46
#else
# define MIN_FIELD_WIDTH 31
#endif
#define STR(x) STR1(x)
#define STR1(x) #x
  /* This must be large enough to accurately hold any value.  */
  char buffer[MIN_FIELD_WIDTH+1];
  char *out;
  char *digits;
  int e;
  char expchar;
  format_token ft;
  int w;
  int d;
  int edigits;
  int ndigits;
  /* Number of digits before the decimal point.  */
  int nbefore;
  /* Number of zeros after the decimal point.  */
  int nzero;
  /* Number of digits after the decimal point.  */
  int nafter;
  /* Number of zeros after the decimal point, whatever the precision.  */
  int nzero_real;
  int leadzero;
  int nblanks;
  int i;
  sign_t sign;
  double abslog;

  ft = f->format;
  w = f->u.real.w;
  d = f->u.real.d;

  nzero_real = -1;


  /* We should always know the field width and precision.  */
  if (d < 0)
    internal_error (&dtp->common, "Unspecified precision");

  /* Use sprintf to print the number in the format +D.DDDDe+ddd
     For an N digit exponent, this gives us (MIN_FIELD_WIDTH-5)-N digits
     after the decimal point, plus another one before the decimal point.  */
  sign = calculate_sign (dtp, value < 0.0);
  if (value < 0)
    value = -value;

  /* Printf always prints at least two exponent digits.  */
  if (value == 0)
    edigits = 2;
  else
    {
#if defined(HAVE_GFC_REAL_10) || defined(HAVE_GFC_REAL_16)
      abslog = fabs((double) log10l(value));
#else
      abslog = fabs(log10(value));
#endif
      if (abslog < 100)
	edigits = 2;
      else
        edigits = 1 + (int) log10(abslog);
    }

  if (ft == FMT_F || ft == FMT_EN
      || ((ft == FMT_D || ft == FMT_E) && dtp->u.p.scale_factor != 0))
    {
      /* Always convert at full precision to avoid double rounding.  */
      ndigits = MIN_FIELD_WIDTH - 4 - edigits;
    }
  else
    {
      /* We know the number of digits, so can let printf do the rounding
	 for us.  */
      if (ft == FMT_ES)
	ndigits = d + 1;
      else
	ndigits = d;
      if (ndigits > MIN_FIELD_WIDTH - 4 - edigits)
	ndigits = MIN_FIELD_WIDTH - 4 - edigits;
    }

  /* #   The result will always contain a decimal point, even if no
   *     digits follow it
   *
   * -   The converted value is to be left adjusted on the field boundary
   *
   * +   A sign (+ or -) always be placed before a number
   *
   * MIN_FIELD_WIDTH  minimum field width
   *
   * *   (ndigits-1) is used as the precision
   *
   *   e format: [-]d.ddde±dd where there is one digit before the
   *   decimal-point character and the number of digits after it is
   *   equal to the precision. The exponent always contains at least two
   *   digits; if the value is zero, the exponent is 00.
   */
  sprintf (buffer, "%+-#" STR(MIN_FIELD_WIDTH) ".*"
	   GFC_REAL_LARGEST_FORMAT "e", ndigits - 1, value);

  /* Check the resulting string has punctuation in the correct places.  */
  if (d != 0 && (buffer[2] != '.' || buffer[ndigits + 2] != 'e'))
      internal_error (&dtp->common, "printf is broken");

  /* Read the exponent back in.  */
  e = atoi (&buffer[ndigits + 3]) + 1;

  /* Make sure zero comes out as 0.0e0.  */
  if (value == 0.0)
    e = 0;

  /* Normalize the fractional component.  */
  buffer[2] = buffer[1];
  digits = &buffer[2];

  /* Figure out where to place the decimal point.  */
  switch (ft)
    {
    case FMT_F:
      nbefore = e + dtp->u.p.scale_factor;
      if (nbefore < 0)
	{
	  nzero = -nbefore;
          nzero_real = nzero;
	  if (nzero > d)
	    nzero = d;
	  nafter = d - nzero;
	  nbefore = 0;
	}
      else
	{
	  nzero = 0;
	  nafter = d;
	}
      expchar = 0;
      break;

    case FMT_E:
    case FMT_D:
      i = dtp->u.p.scale_factor;
      if (value != 0.0)
	e -= i;
      if (i < 0)
	{
	  nbefore = 0;
	  nzero = -i;
	  nafter = d + i;
	}
      else if (i > 0)
	{
	  nbefore = i;
	  nzero = 0;
	  nafter = (d - i) + 1;
	}
      else /* i == 0 */
	{
	  nbefore = 0;
	  nzero = 0;
	  nafter = d;
	}

      if (ft == FMT_E)
	expchar = 'E';
      else
	expchar = 'D';
      break;

    case FMT_EN:
      /* The exponent must be a multiple of three, with 1-3 digits before
	 the decimal point.  */
      if (value != 0.0)
        e--;
      if (e >= 0)
	nbefore = e % 3;
      else
	{
	  nbefore = (-e) % 3;
	  if (nbefore != 0)
	    nbefore = 3 - nbefore;
	}
      e -= nbefore;
      nbefore++;
      nzero = 0;
      nafter = d;
      expchar = 'E';
      break;

    case FMT_ES:
      if (value != 0.0)
        e--;
      nbefore = 1;
      nzero = 0;
      nafter = d;
      expchar = 'E';
      break;

    default:
      /* Should never happen.  */
      internal_error (&dtp->common, "Unexpected format token");
    }

  /* Round the value.  */
  if (nbefore + nafter == 0)
    {
      ndigits = 0;
      if (nzero_real == d && digits[0] >= '5')
        {
          /* We rounded to zero but shouldn't have */
          nzero--;
          nafter = 1;
          digits[0] = '1';
          ndigits = 1;
        }
    }
  else if (nbefore + nafter < ndigits)
    {
      ndigits = nbefore + nafter;
      i = ndigits;
      if (digits[i] >= '5')
	{
	  /* Propagate the carry.  */
	  for (i--; i >= 0; i--)
	    {
	      if (digits[i] != '9')
		{
		  digits[i]++;
		  break;
		}
	      digits[i] = '0';
	    }

	  if (i < 0)
	    {
	      /* The carry overflowed.  Fortunately we have some spare space
		 at the start of the buffer.  We may discard some digits, but
		 this is ok because we already know they are zero.  */
	      digits--;
	      digits[0] = '1';
	      if (ft == FMT_F)
		{
		  if (nzero > 0)
		    {
		      nzero--;
		      nafter++;
		    }
		  else
		    nbefore++;
		}
	      else if (ft == FMT_EN)
		{
		  nbefore++;
		  if (nbefore == 4)
		    {
		      nbefore = 1;
		      e += 3;
		    }
		}
	      else
		e++;
	    }
	}
    }

  /* Calculate the format of the exponent field.  */
  if (expchar)
    {
      edigits = 1;
      for (i = abs (e); i >= 10; i /= 10)
	edigits++;

      if (f->u.real.e < 0)
	{
	  /* Width not specified.  Must be no more than 3 digits.  */
	  if (e > 999 || e < -999)
	    edigits = -1;
	  else
	    {
	      edigits = 4;
	      if (e > 99 || e < -99)
		expchar = ' ';
	    }
	}
      else
	{
	  /* Exponent width specified, check it is wide enough.  */
	  if (edigits > f->u.real.e)
	    edigits = -1;
	  else
	    edigits = f->u.real.e + 2;
	}
    }
  else
    edigits = 0;

  /* Pick a field size if none was specified.  */
  if (w <= 0)
    w = nbefore + nzero + nafter + (sign != SIGN_NONE ? 2 : 1);

  /* Create the ouput buffer.  */
  out = write_block (dtp, w);
  if (out == NULL)
    return;

  /* Zero values always output as positive, even if the value was negative
     before rounding.  */
  for (i = 0; i < ndigits; i++)
    {
      if (digits[i] != '0')
	break;
    }
  if (i == ndigits)
    sign = calculate_sign (dtp, 0);

  /* Work out how much padding is needed.  */
  nblanks = w - (nbefore + nzero + nafter + edigits + 1);
  if (sign != SIGN_NONE)
    nblanks--;

  /* Check the value fits in the specified field width.  */
  if (nblanks < 0 || edigits == -1)
    {
      star_fill (out, w);
      return;
    }

  /* See if we have space for a zero before the decimal point.  */
  if (nbefore == 0 && nblanks > 0)
    {
      leadzero = 1;
      nblanks--;
    }
  else
    leadzero = 0;

  /* Pad to full field width.  */


  if ( ( nblanks > 0 ) && !dtp->u.p.no_leading_blank)
    {
      memset (out, ' ', nblanks);
      out += nblanks;
    }

  /* Output the initial sign (if any).  */
  if (sign == SIGN_PLUS)
    *(out++) = '+';
  else if (sign == SIGN_MINUS)
    *(out++) = '-';

  /* Output an optional leading zero.  */
  if (leadzero)
    *(out++) = '0';

  /* Output the part before the decimal point, padding with zeros.  */
  if (nbefore > 0)
    {
      if (nbefore > ndigits)
	i = ndigits;
      else
	i = nbefore;

      memcpy (out, digits, i);
      while (i < nbefore)
	out[i++] = '0';

      digits += i;
      ndigits -= i;
      out += nbefore;
    }
  /* Output the decimal point.  */
  *(out++) = '.';

  /* Output leading zeros after the decimal point.  */
  if (nzero > 0)
    {
      for (i = 0; i < nzero; i++)
	*(out++) = '0';
    }

  /* Output digits after the decimal point, padding with zeros.  */
  if (nafter > 0)
    {
      if (nafter > ndigits)
	i = ndigits;
      else
	i = nafter;

      memcpy (out, digits, i);
      while (i < nafter)
	out[i++] = '0';

      digits += i;
      ndigits -= i;
      out += nafter;
    }

  /* Output the exponent.  */
  if (expchar)
    {
      if (expchar != ' ')
	{
	  *(out++) = expchar;
	  edigits--;
	}
#if HAVE_SNPRINTF
      snprintf (buffer, sizeof (buffer), "%+0*d", edigits, e);
#else
      sprintf (buffer, "%+0*d", edigits, e);
#endif
      memcpy (out, buffer, edigits);
    }

  if (dtp->u.p.no_leading_blank)
    {
      out += edigits;
      memset( out , ' ' , nblanks );
      dtp->u.p.no_leading_blank = 0;
    }
#undef STR
#undef STR1
#undef MIN_FIELD_WIDTH
}
예제 #27
0
파일: ransack.c 프로젝트: bareid/mangle
/*------------------------------------------------------------------------------
  Generate random az, el positions within mask defined by poly.
  The results are written to out_filename.

   Input: out_filename = name of file to write to;
			"" or "-" means write to standard output.
	  fmt = pointer to format structure.
	  npoly = number of polygons in poly array.
	  npolysmax = maximum number of polygons in poly array.
	  poly = array of pointers to polygons.
	  mtol = initial tolerance angle for multiple intersections.
  Return value: number of random points generated,
		or -1 if error occurred.
*/
int ransack(char *out_filename, format *fmt, int npoly, int npolysmax, polygon *poly[/*npolysmax*/])
{
/* number of extra caps to allocate to polygon, to allow for expansion */
#define DNP			4
/* length of state vector for random number generator */
#define STATELEN		256
    static char state[STATELEN], stateo[STATELEN];
#define AZEL_STR_LEN		32
    char output[] = "output";
    char az_str[AZEL_STR_LEN], el_str[AZEL_STR_LEN];
    int dnp, dnwl, i, idwidth, ier, in, inull, ip, ipmin, ipoly, iprune, irandom, lassoed, np, nwl, tries, verb, width, k;
    long long idmin,idmax;
    int *dlasso=0x0, *lasso=0x0;
    long double area, cmmin, cmi, phi, rpoly, si, tol, w, wcum, x, y, z;
    long double *wpoly;
    vec rp, xi, yi;
    azel v;
    char *out_fn;
    FILE *outfile;

    /* open out_filename for writing */
    if (!out_filename || strcmp(out_filename, "-") == 0) {
	outfile = stdout;
	out_fn = output;
    } else {
	outfile = fopen(out_filename, "w");
	if (!outfile) {
	    fprintf(stderr, "ransack: cannot open %s for writing\n", out_filename);
	    goto error;
	}
	out_fn = out_filename;
    }

    /* advise angular units */
    if (fmt->outunit != fmt->inunit) {
	msg("units of output az, el angles will be ");
	switch (fmt->outunit) {
#include "angunit.h"
	}
	msg("\n");
    }

    /* initialize random number generator used by ransack() */
    initstate(seed, state, STATELEN);
    /* initialize random number generator used by ikrand() */
    initstate(seed, stateo, STATELEN);

    /* prune polygons, discarding those with zero weight * area */
    msg("pruning %d polygons ...\n", npoly);
    ier = 0;
    inull = 0;
    np = 0;
    for (ipoly = 0; ipoly < npoly; ipoly++) {
	/* zero weight polygon */
	if (poly[ipoly]->weight == 0.) {
            inull++;
	    free_poly(poly[ipoly]);
	    poly[ipoly] = 0x0;
	} else {
	/* prune polygon */
	    iprune = prune_poly(poly[ipoly], mtol);
	    /* error */
	    if (iprune == -1) {
		ier++;
		free_poly(poly[ipoly]);
		poly[ipoly] = 0x0;
		fprintf(stderr, "ransack: failed to prune polygon %d; discard it\n", ipoly);
		/* goto error; */
	    /* zero area polygon */
	    } else if (iprune >= 2) {
		inull++;
		free_poly(poly[ipoly]);
		poly[ipoly] = 0x0;
	    } else {
		np++;
	    }
	}
    }
   /*copy down non-null polygons*/
    k=0;
    for(ipoly = 0; ipoly < npoly; ipoly++){
      if(poly[ipoly]){
	poly[k++]=poly[ipoly];
      }
    }
    /*after copying non-null polygons, k should be equal to np */
    if(k!=np){
      fprintf(stderr, "ransack: should be left with %d non-null polygons, but actually have %d\n",np,k);
    }

    /*nullify the rest of the array, but don't free, since pointers have been copied above*/
    for(ipoly=np; ipoly < npoly; ipoly++){
      poly[ipoly]=0x0;
    }

    if (ier > 0) {
	msg("discarding %d unprunable polygons\n", ier);
    }
    if (inull > 0) {
	msg("discarding %d polygons with zero weight * area\n", inull);
    }
    /* number of polygons with finite weight * area */
    npoly = np;

    /* no polygons */
    if (npoly == 0) {
	fprintf(stderr, "ransack: no polygons to generate random points inside!\n");
	goto error;
    }

    /* pre-lasso polygons if there are many random points */
    if (nrandom >= npoly) {
	msg("lassoing %d polygons ...\n", npoly);

	/* lasso each polygon */
	np = npoly;
	for (ipoly = 0; ipoly < npoly; ipoly++) {
	    ier = lasso_poly(&poly[ipoly], npolysmax - np, &poly[np], mtol, &dnp);
	    if (ier == -1) {
		fprintf(stderr, "ransack: UHOH at polygon %lld; continuing ...\n", poly[ipoly]->id);
	    }

	    /* lassoed polygons are an improvement over original polygon */
	    if (dnp > 0) {
		/* check whether exceeded maximum number of polygons */
		if (np + dnp > npolysmax) {
		    fprintf(stderr, "ransack: total number of polygons exceeded maximum %d\n", npolysmax);
		    fprintf(stderr, "if you need more space, enlarge NPOLYSMAX in defines.h, and recompile\n");
		    goto error;
		}

		/* decrement dnp by 1 */
		dnp--;

		/* increment number of polygons */
		np += dnp;

		/* move last polygon part into poly[ipoly] */
		free_poly(poly[ipoly]);
		poly[ipoly] = poly[np];
		poly[np] = 0x0;
	    }
	}

	/* revised number of polygons */
	npoly = np;

	/* flag that all polygons have been lassoed */
	lassoed = 1;

    /* two few random points to make it worth pre-lassoing */
    } else {
	/* flag that all polygons have not been lassoed */
	lassoed = 0;

    }

    /* allocate memory for wpoly array */
    nwl = npoly;
    wpoly = (long double *) malloc(sizeof(long double) * nwl);
    if (!wpoly) {
        fprintf(stderr, "ransack: failed to allocate memory for %d long doubles\n", nwl);
        goto error;
    }
    if (!lassoed) {
	/* allocate memory for lasso and dlasso arrays */
	lasso = (int *) malloc(sizeof(int) * nwl);
	if (!lasso) {
	    fprintf(stderr, "ransack: failed to allocate memory for %d ints\n", nwl);
	    goto error;
	}
	dlasso = (int *) malloc(sizeof(int) * nwl);
	if (!dlasso) {
	    fprintf(stderr, "ransack: failed to allocate memory for %d ints\n", nwl);
	    goto error;
	}

	/* initialize dlasso array to zero */
	for (ipoly = 0; ipoly < nwl; ipoly++) dlasso[ipoly] = 0;
    }

    /* largest width of polygon id number */
    idmin = 0;
    idmax = 0;
    for (ipoly = 0; ipoly < npoly; ipoly++) {
	if (poly[ipoly]->id < idmin) idmin = poly[ipoly]->id;
	if (poly[ipoly]->id > idmax) idmax = poly[ipoly]->id;
    }
    idmin = ((idmin < 0)? floorl(log10l((long double)-idmin)) + 2 : 1);
    idmax = ((idmax > 0)? floorl(log10l((long double)idmax)) + 1 : 1);
    idwidth = ((idmin > idmax)? idmin : idmax);

    /* write header */
    wrangle(0., fmt->outunit, fmt->outprecision, AZEL_STR_LEN, az_str);
    width = strlen(az_str);
    if (fmt->outunit == 'h') {
	sprintf(az_str, "az(hms)");
	sprintf(el_str, "el(dms)");
    } else {
	sprintf(az_str, "az(%c)", fmt->outunit);
	sprintf(el_str, "el(%c)", fmt->outunit);
    }
    fprintf(outfile, "%*s\t%*s\t%*s\n", width, az_str, width, el_str, idwidth, "id");

    /* accept error messages from garea */
    /* unprunable polygons were already discarded, so garea should give no errors */
    verb = 1;

    /* cumulative area times weight of polygons */
    w = 0.;
    for (ipoly = 0; ipoly < npoly; ipoly++) {
	/* skip null polygons */
	if (poly[ipoly]) {
	    /* area of polygon */
	    tol = mtol;
	    ier = garea(poly[ipoly], &tol, verb, &area);
	    if (ier) goto error;
	    /* accumulate weight times area */
	    w += poly[ipoly]->weight * area;
	}
	wpoly[ipoly] = w;
    }
    wcum = w;

    /* random points */
    if (strcmp(out_fn, output) != 0) {
	msg("generating %d random points from seed %u in %d polygons ...\n", nrandom, seed, npoly);
    }
    for (irandom = 0; irandom < nrandom; irandom++) {

	/* random number in interval [0, 1) wcum */
	setstate(state);
	rpoly = drandom() * wcum;
	setstate(stateo);

	/* which polygon to put random point in */
	ipoly = search(npoly, wpoly, rpoly);

	/* guard against roundoff */
	if (ipoly >= npoly) {
	    fprintf(stderr, "ransack: %d should be < %d (i.e. %.15Lg < %.15Lg)\n", ipoly, npoly, rpoly, wpoly[npoly - 1]);
	    ipoly = npoly - 1;
	}

	/* all polygons have not been lassoed */
	if (!lassoed) {

	    /* polygon has not yet been lassoed */
	    if  (dlasso[ipoly] == 0) {

		/* lasso polygon */
		ier = lasso_poly(&poly[ipoly], npolysmax - np, &poly[np], mtol, &dnp);
		if (ier == -1) {
		    fprintf(stderr, "ransack: UHOH at polygon %lld; continuing ...\n", poly[ipoly]->id);
		}

		/* go with original polygon */
		if (dnp == 0) {
		    /* lasso, dlasso */
		    lasso[ipoly] = ipoly;
		    dlasso[ipoly] = 1;

		/* lassoed polygons are an improvement over original */
		} else {
		    /* check whether exceeded maximum number of polygons */
		    if (np + dnp > npolysmax) {
			fprintf(stderr, "ransack: total number of polygons exceeded maximum %d\n", npolysmax);
			fprintf(stderr, "if you need more space, enlarge NPOLYSMAX in defines.h, and recompile\n");
			goto error;
		    }

		    /* just one lassoed polygon */
		    if (dnp == 1) {
			/* move last polygon part into poly[ipoly] */
			free_poly(poly[ipoly]);
			poly[ipoly] = poly[np];
			poly[np] = 0x0;

			/* lasso, dlasso */
			lasso[ipoly] = ipoly;
			dlasso[ipoly] = 1;

		    /* more than one lassoed polygon */
		    } else {
			/* enlarge memory for wpoly, lasso, and dlasso arrays */
			if (np + dnp > nwl) {
			    dnwl = dnp + 1024;
			    wpoly = (long double *) realloc(wpoly, sizeof(long double) * (nwl + dnwl));
			    if (!wpoly) {
				fprintf(stderr, "ransack: failed to reallocate memory for %d long doubles\n", nwl + dnwl);
				goto error;
			    }
			    lasso = (int *) realloc(lasso, sizeof(int) * (nwl + dnwl));
			    if (!lasso) {
				fprintf(stderr, "ransack: failed to reallocate memory for %d ints\n", nwl + dnwl);
				goto error;
			    }
			    dlasso = (int *) realloc(dlasso, sizeof(int) * (nwl + dnwl));
			    if (!dlasso) {
				fprintf(stderr, "ransack: failed to reallocate memory for %d ints\n", nwl + dnwl);
				goto error;
			    }

			    /* initialize new part of lasso and dlasso arrays to inconsistent values */
			    for (ipoly = nwl; ipoly < nwl + dnwl; ipoly++) lasso[ipoly] = 1;
			    for (ipoly = nwl; ipoly < nwl + dnwl; ipoly++) dlasso[ipoly] = 0;

			    /* revised size of wpoly, lasso, and dlasso arrays */
			    nwl += dnwl;
			}

			/* lasso, dlasso */
			lasso[ipoly] = np;
			dlasso[ipoly] = dnp;

			/* cumulative weight times area of lassoed polygons */
			w = (ipoly == 0)? 0. : wpoly[ipoly-1];
			for (ip = np; ip < np + dnp; ip++) {
			    /* area of polygon */
			    tol = mtol;
			    ier = garea(poly[ip], &tol, verb, &area);
			    if (ier) goto error;
			    /* accumulate area times weight */
			    w += poly[ip]->weight * area;
			    wpoly[ip] = w;
			}

			/* increment number of polygons */
			np += dnp;
		    }

		}

	    }

	    /* polygon was partitioned into at least two */
	    if (dlasso[ipoly] >= 2) {
		/* which polygon to put random point in */
		ip = search(dlasso[ipoly], &wpoly[lasso[ipoly]], rpoly);

		/* guard against roundoff */
		if (ip >= lasso[ipoly] + dlasso[ipoly]) {
		    fprintf(stderr, "ransack: %d should be < %d (i.e. %.15Lg < %.15Lg)\n", ip, lasso[ipoly] + dlasso[ipoly], rpoly, wpoly[lasso[ipoly] + dlasso[ipoly] - 1]);
		    ip = lasso[ipoly] + dlasso[ipoly] - 1;
		}

		/* revised polygon number to put random point in */
		ipoly = ip;
	    }
	}

	/* smallest cap of polygon */
	cmminf(poly[ipoly], &ipmin, &cmmin);

	/* random point within polygon */
	tries = 0;
	do {
	    tries++;
	    /* random point within smallest cap */
	    setstate(state);
	    phi = TWOPI * drandom();
	    cmi = cmmin * drandom();
	    setstate(stateo);
	    /* coordinates of random point in cap frame */
	    si=sqrtl(cmi * (2. - cmi));
	    x = si * cosl(phi);
	    y = si * sinl(phi);
	    z = 1. - cmi;
	    /* polygon has caps */
	    if (poly[ipoly]->np > 0) {
		if (poly[ipoly]->cm[ipmin] < 0.) z = -z;
		/* Cartesian axes with z-axis along cap axis */
		gaxisi_(poly[ipoly]->rp[ipmin], xi, yi);
		/* coordinates of random point */
		for (i = 0; i < 3; i++) rp[i] = x * xi[i] + y * yi[i] + z * poly[ipoly]->rp[ipmin][i];
		/* whether random point is inside polygon */
		in = gptin(poly[ipoly], rp);
	    /* polygon has no caps, so is the whole sphere */
	    } else {
		rp[0] = x;
		rp[1] = y;
		rp[2] = z;
		in = 1;
	    }
	} while (!in);

	/* convert unit vector to az, el */
	rp_to_azel(rp, &v);
	v.az -= floorl(v.az / TWOPI) * TWOPI;

	/* convert az and el from radians to output units */
	scale_azel(&v, 'r', fmt->outunit);

	/* write result */
	wrangle(v.az, fmt->outunit, fmt->outprecision, AZEL_STR_LEN, az_str);
	wrangle(v.el, fmt->outunit, fmt->outprecision, AZEL_STR_LEN, el_str);
	fprintf(outfile, "%s\t%s\t%*lld\n", az_str, el_str, idwidth, poly[ipoly]->id);
	/* fprintf(outfile, "%s %s %d %d %d %Lg %Lg %Lg %Lg %d %d\n", az_str, el_str, irandom, ipoly, tries, wcum, rpoly / wcum, area, TWOPI * cmmin / area, ipmin, poly[ipoly]->np); */

    }

    /* advise */
    if (outfile != stdout) {
	msg("ransack: %d random positions written to %s\n", nrandom, out_fn);
    }

    return(nrandom);

    /* error returns */
    error:
    return(-1);
}
예제 #28
0
파일: polyid.c 프로젝트: abensonca/mangle
/*------------------------------------------------------------------------------
  Id numbers of polygons containing az, el positions.
  The az, el positions are read from in_filename,
  and the results are written to out_filename.
  Implemented as interpretive read/write, to permit interactive behaviour.

   Input: in_filename = name of file to read from;
			"" or "-" means read from standard input.
	  out_filename = name of file to write to;
			"" or "-" means write to standard output.
	  fmt = pointer to format structure.
	  poly = array of pointers to polygons.
	  npoly = number of polygons in poly array.
  Return value: number of lines written,
		or -1 if error occurred.
*/
int poly_ids(char *in_filename, char *out_filename, format *fmt, int npoly, polygon *poly[/*npoly*/])
{
#define AZEL_STR_LEN	32
    char input[] = "input", output[] = "output";
    char *word, *next;
    char az_str[AZEL_STR_LEN], el_str[AZEL_STR_LEN];
    int i, idwidth, ird, len, nid, nids, nid0, nid2, np;
    long long idmin, idmax;
    long long *id;
    long double *weight;
    azel v;
    char *out_fn;
    FILE *outfile;
    int *start;
    int *total;
    int *parent_pixels;
    int p, res, max_pixel, ier, sorted;

    ier=-1;
    sorted=0;
    while(ier!=0){
      max_pixel= poly[npoly-1]->pixel; 
      res_max=get_res(max_pixel, scheme);
      max_pixel=pixel_start(res_max+1,scheme);
      
      /* allocate memory for pixel info arrays start and total */ 
      msg("res_max=%d, max_pixel=%d\n",res_max,max_pixel);
      start = (int *) malloc(sizeof(int) * max_pixel);
      if (!start) {
	fprintf(stderr, "polyid: failed to allocate memory for %d integers\n", max_pixel);
	return(-1);
      }
      total = (int *) malloc(sizeof(int) * max_pixel);
      if (!total) {
	fprintf(stderr, "polyid: failed to allocate memory for %d integers\n", max_pixel);
	return(-1);
      }
      parent_pixels = (int *) malloc(sizeof(int) * (res_max+1));
      if (!parent_pixels) {
	fprintf(stderr, "polyid: failed to allocate memory for %d integers\n", res_max+1);
	return(-1);
      }
      
      /* build lists of starting indices of each pixel and total number of polygons in each pixel*/
      
      ier=pixel_list(npoly, poly, max_pixel, start, total);
      if (ier == -1) {
	// if pixel_list returns an error, try sorting the polygons and trying again
	if(!sorted){
	  msg("sorting polygons...\n");
	  poly_sort(npoly,poly,'p');
	  sorted=1;
	}
	else{
	  fprintf(stderr, "poly_ids: error building pixel index lists\n");
	  return(-1);
	}
      } 
    }
    
    /* open in_filename for reading */
    if (!in_filename || strcmp(in_filename, "-") == 0) {
	file.file = stdin;
	file.name = input;
    } else {
	file.file = fopen(in_filename, "r");
	if (!file.file) {
	    fprintf(stderr, "cannot open %s for reading\n", in_filename);
	    return(-1);
	}
	file.name = in_filename;
    }
    file.line_number = 0;

    /* open out_filename for writing */
    if (!out_filename || strcmp(out_filename, "-") == 0) {
	outfile = stdout;
	out_fn = output;
    } else {
	outfile = fopen(out_filename, "w");
	if (!outfile) {
	    fprintf(stderr, "cannot open %s for writing\n", out_filename);
	    return(-1);
	}
	out_fn = out_filename;
    }

    /* advise angular units */
    msg("will take units of input az, el angles in %s to be ", file.name);
    switch (fmt->inunit) {
#include "angunit.h"
    }
    msg("\n");
    if (fmt->outunit != fmt->inunit) {
	msg("units of output az, el angles will be ");
	switch (fmt->outunit) {
#include "angunit.h"
	}
	msg("\n");
    }

    /* largest width of polygon id number */
    idmin = 0;
    idmax = 0;
    for (i = 0; i < npoly; i++) {
	if (!poly[i]) continue;
	if (poly[i]->id < idmin) idmin = poly[i]->id;
	if (poly[i]->id > idmax) idmax = poly[i]->id;
    }
    idmin = ((idmin < 0)? floorl(log10l((long double)-idmin)) + 2 : 1);
    idmax = ((idmax > 0)? floorl(log10l((long double)idmax)) + 1 : 1);
    idwidth = ((idmin > idmax)? idmin : idmax);

    /* write header */
    v.az = 0.;
    wrangle(v.az, fmt->outunit, fmt->outprecision, AZEL_STR_LEN, az_str);
    len = strlen(az_str);
    if (fmt->outunit == 'h') {
	sprintf(az_str, "az(hms)");
	sprintf(el_str, "el(dms)");
    } else {
	sprintf(az_str, "az(%c)", fmt->outunit);
	sprintf(el_str, "el(%c)", fmt->outunit);
    }
    fprintf(outfile, "%*s %*s", len, az_str, len, el_str);
    if (npoly > 0){
      if(polyid_weight==1){
	fprintf(outfile, " polygon_weights");
      }
      else{
	fprintf(outfile, " polygon_ids");	
      }
    }
    fprintf(outfile, "\n");

    /* interpretive read/write loop */
    np = 0;
    nid = 0;
    nids = 0;
    nid0 = 0;
    nid2 = 0;
    while (1) {
	/* read line */
	ird = rdline(&file);
	/* serious error */
	if (ird == -1) return(-1);
	/* EOF */
	if (ird == 0) break;

	/* read <az> */
	word = file.line;
	ird = rdangle(word, &next, fmt->inunit, &v.az);
	/* skip header */
	if (ird != 1 && np == 0) continue;
	/* otherwise exit on unrecognized characters */
	if (ird != 1) break;

	/* read <el> */
	word = next;
	ird = rdangle(word, &next, fmt->inunit, &v.el);
	/* skip header */
	if (ird != 1 && np == 0) continue;
	/* otherwise exit on unrecognized characters */
	if (ird != 1) break;

	/* convert az and el from input units to radians */
	scale_azel(&v, fmt->inunit, 'r');
	
	//find out what pixel the az el point is in at the maximum resolution
	p=which_pixel(v.az, v.el, res_max, scheme);
	//get the list of all the possible parent pixels
	get_parent_pixels(p, parent_pixels, scheme);

	nid=0;
	for(res=res_max;res>=0;res--){
	  p=parent_pixels[res];
	  //if this pixel isn't in the polygon list, go to next parent pixel
	  if(total[p]==0) continue;
	  // id numbers of the polygons containing position az, el 
	  nid = poly_id(total[p], &poly[start[p]], v.az, v.el, &id, &weight);
	}
	
	/* convert az and el from radians to output units */
	scale_azel(&v, 'r', fmt->outunit);

	/* write result */
	wrangle(v.az, fmt->outunit, fmt->outprecision, AZEL_STR_LEN, az_str);
	wrangle(v.el, fmt->outunit, fmt->outprecision, AZEL_STR_LEN, el_str);
	fprintf(outfile, "%s %s", az_str, el_str);
	for (i = 0; i < nid; i++) {
	  if(polyid_weight==1){
	    fprintf(outfile, " %.18Lg", weight[i]);
	  } else{
	    fprintf(outfile, " %*lld", idwidth, id[i]);
	  }
	}
	fprintf(outfile, "\n");
	fflush(outfile);

        /* increment counters of results */
	np++;
	nids += nid;
	if (nid == 0) {
	  nid0++;
	} else if (nid >= 2) {
	  nid2++;
	}
    }

    /* advise */
    if (nid0 > 0) msg("%d points were not inside any polygon\n", nid0);
    if (nid2 > 0) msg("%d points were inside >= 2 polygons\n", nid2);

    if (outfile != stdout) {
      if(polyid_weight==1){
	msg("polyid: %d weights at %d positions written to %s\n", nids, np, out_fn);
      } else {
	msg("polyid: %d id numbers at %d positions written to %s\n", nids, np, out_fn);
      }
    }
    
    free(start);
    free(total);
    free(parent_pixels);

    return(np);
}
예제 #29
0
TEST(math, log10l) {
  ASSERT_DOUBLE_EQ(3.0L, log10l(1000.0L));
}
예제 #30
0
npy_longdouble npy_log10l(npy_longdouble x)
{
    return log10l(x);
}