3 #include <gsl/gsl_roots.h>
4 #include <gsl/gsl_sf.h>
5 #include <libpspp/assertion.h>
6 #include <libpspp/pool.h>
9 const struct substring empty_string = {NULL, 0};
12 expr_error (void *aux UNUSED, const char *format, ...)
17 m.category = MSG_SYNTAX;
18 m.severity = MSG_ERROR;
19 va_start (args, format);
20 m.text = xvasprintf (format, args);
27 expr_ymd_to_ofs (double year, double month, double day)
33 if (y != year || m != month || d != day)
35 msg (SE, _("One of the arguments to a DATE function is not an integer. "
36 "The result will be system-missing."));
40 return calendar_gregorian_to_offset (y, m, d, expr_error, NULL);
44 expr_ymd_to_date (double year, double month, double day)
46 double ofs = expr_ymd_to_ofs (year, month, day);
47 return ofs != SYSMIS ? ofs * DAY_S : SYSMIS;
51 expr_wkyr_to_date (double week, double year)
57 msg (SE, _("The week argument to DATE.WKYR is not an integer. "
58 "The result will be system-missing."));
61 else if (w < 1 || w > 53)
63 msg (SE, _("The week argument to DATE.WKYR is outside the acceptable "
65 "The result will be system-missing."));
70 double yr_1_1 = expr_ymd_to_ofs (year, 1, 1);
72 return DAY_S * (yr_1_1 + WEEK_DAY * (w - 1));
79 expr_yrday_to_date (double year, double yday)
85 msg (SE, _("The day argument to DATE.YRDAY is not an integer. "
86 "The result will be system-missing."));
89 else if (yd < 1 || yd > 366)
91 msg (SE, _("The day argument to DATE.YRDAY is outside the acceptable "
93 "The result will be system-missing."));
98 double yr_1_1 = expr_ymd_to_ofs (year, 1, 1);
100 return DAY_S * (yr_1_1 + yd - 1.);
107 expr_yrmoda (double year, double month, double day)
109 if (year >= 0 && year <= 99)
111 else if (year != (int) year && year > 47516)
113 msg (SE, _("The year argument to YRMODA is greater than 47516. "
114 "The result will be system-missing."));
118 return expr_ymd_to_ofs (year, month, day);
135 /* Return X rounded toward zero. */
139 return x >= 0.0 ? floor (x) : ceil (x);
141 #endif /* !HAVE_TRUNC */
143 /* Stores in *UNIT the unit whose name is NAME.
145 static enum date_unit
146 recognize_unit (struct substring name, enum date_unit *unit)
151 const struct substring name;
153 static const struct unit_name unit_names[] =
155 { DATE_YEARS, SS_LITERAL_INITIALIZER ("years") },
156 { DATE_QUARTERS, SS_LITERAL_INITIALIZER ("quarters") },
157 { DATE_MONTHS, SS_LITERAL_INITIALIZER ("months") },
158 { DATE_WEEKS, SS_LITERAL_INITIALIZER ("weeks") },
159 { DATE_DAYS, SS_LITERAL_INITIALIZER ("days") },
160 { DATE_HOURS, SS_LITERAL_INITIALIZER ("hours") },
161 { DATE_MINUTES, SS_LITERAL_INITIALIZER ("minutes") },
162 { DATE_SECONDS, SS_LITERAL_INITIALIZER ("seconds") },
164 const int unit_name_cnt = sizeof unit_names / sizeof *unit_names;
166 const struct unit_name *un;
168 for (un = unit_names; un < &unit_names[unit_name_cnt]; un++)
169 if (ss_equals_case (un->name, name))
175 msg (SE, _("Unrecognized date unit \"%.*s\". "
176 "Valid date units are \"years\", \"quarters\", \"months\", "
177 "\"weeks\", \"days\", \"hours\", \"minutes\", and \"seconds\"."),
178 (int) ss_length (name), ss_data (name));
182 /* Returns the number of whole years from DATE1 to DATE2,
183 where a year is defined as the same or later month, day, and
186 year_diff (double date1, double date2)
192 assert (date2 >= date1);
193 calendar_offset_to_gregorian (date1 / DAY_S, &y1, &m1, &d1, &yd1);
194 calendar_offset_to_gregorian (date2 / DAY_S, &y2, &m2, &d2, &yd2);
199 int yd1 = 32 * m1 + d1;
200 int yd2 = 32 * m2 + d2;
202 || (yd2 == yd1 && fmod (date2, DAY_S) < fmod (date1, DAY_S)))
208 /* Returns the number of whole months from DATE1 to DATE2,
209 where a month is defined as the same or later day and time of
212 month_diff (double date1, double date2)
218 assert (date2 >= date1);
219 calendar_offset_to_gregorian (date1 / DAY_S, &y1, &m1, &d1, &yd1);
220 calendar_offset_to_gregorian (date2 / DAY_S, &y2, &m2, &d2, &yd2);
222 diff = ((y2 * 12) + m2) - ((y1 * 12) + m1);
225 || (d2 == d1 && fmod (date2, DAY_S) < fmod (date1, DAY_S))))
230 /* Returns the number of whole quarter from DATE1 to DATE2,
231 where a quarter is defined as three months. */
233 quarter_diff (double date1, double date2)
235 return month_diff (date1, date2) / 3;
238 /* Returns the number of seconds in the given UNIT. */
240 date_unit_duration (enum date_unit unit)
264 /* Returns the span from DATE1 to DATE2 in terms of UNIT_NAME. */
266 expr_date_difference (double date1, double date2, struct substring unit_name)
270 if (!recognize_unit (unit_name, &unit))
276 return (date2 >= date1
277 ? year_diff (date1, date2)
278 : -year_diff (date2, date1));
281 return (date2 >= date1
282 ? quarter_diff (date1, date2)
283 : -quarter_diff (date2, date1));
286 return (date2 >= date1
287 ? month_diff (date1, date2)
288 : -month_diff (date2, date1));
295 return trunc ((date2 - date1) / date_unit_duration (unit));
301 /* How to deal with days out of range for a given month. */
304 SUM_ROLLOVER, /* Roll them over to the next month. */
305 SUM_CLOSEST /* Use the last day of the month. */
308 /* Stores in *METHOD the method whose name is NAME.
311 recognize_method (struct substring method_name, enum date_sum_method *method)
313 if (ss_equals_case (method_name, ss_cstr ("closest")))
315 *method = SUM_CLOSEST;
318 else if (ss_equals_case (method_name, ss_cstr ("rollover")))
320 *method = SUM_ROLLOVER;
325 msg (SE, _("Invalid DATESUM method. "
326 "Valid choices are \"closest\" and \"rollover\"."));
331 /* Returns DATE advanced by the given number of MONTHS, with
332 day-of-month overflow resolved using METHOD. */
334 add_months (double date, int months, enum date_sum_method method)
339 calendar_offset_to_gregorian (date / DAY_S, &y, &m, &d, &yd);
352 assert (m >= 1 && m <= 12);
354 if (method == SUM_CLOSEST && d > calendar_days_in_month (y, m))
355 d = calendar_days_in_month (y, m);
357 output = calendar_gregorian_to_offset (y, m, d, expr_error, NULL);
358 if (output != SYSMIS)
359 output = (output * DAY_S) + fmod (date, DAY_S);
363 /* Returns DATE advanced by the given QUANTITY of units given in
364 UNIT_NAME, with day-of-month overflow resolved using
367 expr_date_sum (double date, double quantity, struct substring unit_name,
368 struct substring method_name)
371 enum date_sum_method method;
373 if (!recognize_unit (unit_name, &unit)
374 || !recognize_method (method_name, &method))
380 return add_months (date, trunc (quantity) * 12, method);
383 return add_months (date, trunc (quantity) * 3, method);
386 return add_months (date, trunc (quantity), method);
393 return date + quantity * date_unit_duration (unit);
400 compare_string (const struct substring *a, const struct substring *b)
404 for (i = 0; i < a->length && i < b->length; i++)
405 if (a->string[i] != b->string[i])
406 return a->string[i] < b->string[i] ? -1 : 1;
407 for (; i < a->length; i++)
408 if (a->string[i] != ' ')
410 for (; i < b->length; i++)
411 if (b->string[i] != ' ')
417 count_valid (double *d, size_t d_cnt)
423 for (i = 0; i < d_cnt; i++)
424 valid_cnt += is_valid (d[i]);
429 alloc_string (struct expression *e, size_t length)
433 s.string = pool_alloc (e->eval_pool, length);
438 copy_string (struct expression *e, const char *old, size_t length)
440 struct substring s = alloc_string (e, length);
441 memcpy (s.string, old, length);
445 /* Returns the noncentral beta cumulative distribution function
446 value for the given arguments.
448 FIXME: The accuracy of this function is not entirely
449 satisfactory. We only match the example values given in AS
450 310 to the first 5 significant digits. */
452 ncdf_beta (double x, double a, double b, double lambda)
456 if (x <= 0. || x >= 1. || a <= 0. || b <= 0. || lambda <= 0.)
462 /* Algorithm AS 226. */
463 double x0, a0, beta, temp, gx, q, ax, sumq, sum;
464 double err_max = 2 * DBL_EPSILON;
469 x0 = floor (c - 5.0 * sqrt (c));
473 beta = (gsl_sf_lngamma (a0)
475 - gsl_sf_lngamma (a0 + b));
476 temp = gsl_sf_beta_inc (a0, b, x);
477 gx = exp (a0 * log (x) + b * log (1. - x) - beta - log (a0));
479 q = exp (-c + x0 * log (c)) - gsl_sf_lngamma (x0 + 1.);
491 gx = x * (a + b + iter - 1.) * gx / (a + iter);
497 err_bound = (temp - gx) * sumq;
499 while (iter < iter_max && err_bound > err_max);
505 /* Algorithm AS 310. */
507 int iter, iter_lower, iter_upper, iter1, iter2, j;
508 double t, q, r, psum, beta, s1, gx, fx, temp, ftemp, t0, s0, sum, s;
510 double err_max = 2 * DBL_EPSILON;
516 iter_lower = m - 5. * m_sqrt;
517 iter_upper = m + 5. * m_sqrt;
519 t = -c + m * log (c) - gsl_sf_lngamma (m + 1.);
523 beta = (gsl_sf_lngamma (a + m)
525 - gsl_sf_lngamma (a + m + b));
526 s1 = (a + m) * log (x) + b * log (1. - x) - log (a + m) - beta;
528 ftemp = temp = gsl_sf_beta_inc (a + m, b, x);
533 while (iter1 >= iter_lower && q >= err_max)
537 gx = (a + iter1) / (x * (a + b + iter1 - 1.)) * gx;
544 t0 = (gsl_sf_lngamma (a + b)
545 - gsl_sf_lngamma (a + 1.)
546 - gsl_sf_lngamma (b));
547 s0 = a * log (x) + b * log (1. - x);
550 for (j = 0; j < iter1; j++)
553 s += exp (t0 + s0 + j * log (x));
554 t1 = log (a + b + j) - log (a + 1. + j) + t0;
558 err_bound = (1. - gsl_sf_gamma_inc_P (iter1, c)) * (temp + s);
565 double ebd = err_bound + (1. - psum) * temp;
566 if (ebd < err_max || iter >= iter_upper)
574 gx = x * (a + b + iter2 - 1.) / (a + iter2) * gx;
583 cdf_bvnor (double x0, double x1, double r)
585 double z = x0 * x0 - 2. * r * x0 * x1 + x1 * x1;
586 return exp (-z / (2. * (1 - r * r))) * (2. * M_PI * sqrt (1 - r * r));
590 idf_fdist (double P, double df1, double df2)
592 double temp = gslextras_cdf_beta_Pinv (P, df1 / 2, df2 / 2);
593 return temp * df2 / ((1. - temp) * df1);
597 * Mathlib : A C Library of Special Functions
598 * Copyright (C) 1998 Ross Ihaka
599 * Copyright (C) 2000 The R Development Core Team
601 * This program is free software; you can redistribute it and/or
603 * it under the terms of the GNU General Public License as
605 * the Free Software Foundation; either version 2 of the
607 * (at your option) any later version.
609 * This program is distributed in the hope that it will be
611 * but WITHOUT ANY WARRANTY; without even the implied warranty
613 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
614 * GNU General Public License for more details.
616 * You should have received a copy of the GNU General Public
618 * along with this program; if not, write to the Free Software
619 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
623 /* Returns the density of the noncentral beta distribution with
624 noncentrality parameter LAMBDA. */
626 npdf_beta (double x, double a, double b, double lambda)
628 if (lambda < 0. || a <= 0. || b <= 0.)
630 else if (lambda == 0.)
631 return gsl_ran_beta_pdf (x, a, b);
634 double max_error = 2 * DBL_EPSILON;
636 double term = gsl_ran_beta_pdf (x, a, b);
637 double lambda2 = 0.5 * lambda;
638 double weight = exp (-lambda2);
639 double sum = weight * term;
640 double psum = weight;
642 for (k = 1; k <= max_iter && 1 - psum < max_error; k++) {
643 weight *= lambda2 / k;
644 term *= x * (a + b) / a;
645 sum += weight * term;