Beispiel #1
0
def cochrane(selectionSize, qty_of_selections, significance):
    selectionSize += 1
    partResult1 = significance / (selectionSize - 1)
    params = [partResult1, qty_of_selections, (selectionSize - 1 - 1) * qty_of_selections]
    fischer = f.isf(*params)
    result = fischer / (fischer + (selectionSize - 1 - 1))
    return Decimal(result).quantize(Decimal('.0001')).__float__()
    def test_contrast_profit_deposit_14(self, d):
        """
        理财产品比收益
        :param d:
        :return:
        """
        # prd_key = d(resourceId=get_value("比收益理财产品名称"))
        prd_value = d(resourceId=get_value("比收益理财产品收益"))
        prd_many = d(resourceId=get_value("比收益理财产品收益差额"))
        prd_value_list = []
        prd_many_list = []

        for i in range(prd_value.__len__()):
            prd_value_list.append(Decimal(prd_value[i].get_text()).quantize(Decimal('0.00')))

        print(prd_value_list)

        for i in range(prd_many.__len__()):
            prd_many_value = (prd_many[i].get_text()).translate(str.maketrans('+', ' ')).strip()
            prd_many_list.append(Decimal(prd_many_value).quantize(Decimal('0.00')))

        print(prd_many_list)

        for i in range(prd_value.__len__()-1):
            prd_db = prd_value_list[i] - prd_many_list[i]
            print(prd_value_list[i])
            print("--------------------------")
            print(prd_many_list[i])
            test.assert_equal_save_picture(d, prd_db,  prd_value_list[-1], "收益计算对比")

        Consts.RESULT_LIST.append('True')
Beispiel #3
0
def cohren_value(size_of_selections, qty_of_selections, significance):
    size_of_selections += 1
    partResult1 = significance / (size_of_selections - 1)
    params = [partResult1, qty_of_selections, (size_of_selections - 1 - 1) * qty_of_selections]
    fisher = f.isf(*params)
    result = fisher / (fisher + (size_of_selections - 1 - 1))
    return Decimal(result).quantize(Decimal('.0001')).__float__()
Beispiel #4
0
    def cochran(self, N, m):
        for i in range(N):
            ydisp = 0
            for k in range(m):
                ydisp += (self.ylist[i][k] - self.ymed[i])**2
            ydisp /= m
            self.ydisplist.append(round(ydisp, self.round))

        self.groz = round(
            max(self.ydisplist) / sum(self.ydisplist), self.round)
        f1 = m - 1
        f2 = N
        partresult = self.q / f2
        params = [partresult, f1, (f2 - 1) * f1]
        fisher = f.isf(*params)
        result = fisher / (fisher + (f2 - 1))
        self.gkr = round(
            Decimal(result).quantize(Decimal('.0001')).__float__(), self.round)
        self.f1 = f1
        self.f2 = f2
        Task.printcoch(N)
        if self.groz < self.gkr:
            print(
                "   Gp < Gкр => За критерієм Кохрана дисперсія однорідна з ймовірністю",
                p)
        else:
            print(
                "   Gp > Gкр => За критерієм Кохрана дисперсія неоднорідна з ймовірністю",
                p)
            print("   Збільшуємо m на 1: m = {1}+1 = {0}".format(m + 1, m))
            m += 1
            Task.equation(N, m)
            Task.cochran(N, m)
Beispiel #5
0
 def renderData(data):
     DataFilePath = "files\sampleText.txt"
     pullData = open(DataFilePath, "r").read()
     dataList = pullData.split('\n')
     xList = []
     yList = []
     fmt = '%Y-%m-%d %H:%M:%S.%f'
     for eachLine in dataList:
         if len(eachLine) > 1:
             date, temp, cond, ph = eachLine.split(',')
             timestamp1 = datetime.strptime(date, fmt)
             timestamp2 = datetime.strptime(str(datetime.now()), fmt)
             interval = (timestamp2 - timestamp1)
             if interval.days <= 1:
                 date, time = date.split(' ')
                 hour, minute, second = time.split(':')
                 # xList.append(Decimal(hour))
                 xAxisDateTime = str(timestamp1.date()) + " " + str(
                     timestamp1.hour) + ":00"
                 xList.append(xAxisDateTime)
                 if data == 'temp':
                     yList.append(Decimal(temp))
                 if data == 'cond':
                     yList.append(Decimal(cond))
                 if data == 'ph':
                     yList.append(Decimal(ph))
Beispiel #6
0
def Cochran():
    d1 = disp(1, ylist[0])
    d2 = disp(2, ylist[1])
    d3 = disp(3, ylist[2])
    d4 = disp(4, ylist[3])
    groz = round(max(ydisp) / sum(ydisp), 2)
    partresult = q / (f2 - 1)
    params = [partresult, f1, (f2 - 2) * f1]
    fisher = f.isf(*params)
    result = fisher / (fisher + (f2 - 2))
    gkr = round(Decimal(result).quantize(Decimal('.0001')).__float__(), 2)

    print("\n2)Критерій Кохрана:\n\n  Знайдемо дисперсії по рядках:")
    print("  ", d1, "\n  ", d2, "\n  ", d3, "\n  ", d4, "\n")
    print("   Dmax{{yi}} = {0}\n   Gp = {0}/({1}+{2}+{3}+{4}) = {5}".format(
        max(ydisp), *ydisp, groz))
    print("   f1 = {0} - 1 = {1}, f2 = 4, q = {3}\n   За таблицею Gкр = {2}".
          format(m, f1, gkr, q))
    if groz < gkr:
        print(
            "   Gp < Gкр => За критерієм Кохрана дисперсія однорідна з ймовірністю",
            p)
    else:
        print(
            "   Gp > Gкр => За критерієм Кохрана дисперсія неоднорідна з ймовірністю",
            p)
Beispiel #7
0
 def set_progress(self,
                  current,
                  total,
                  description="",
                  ctype='application/json',
                  cenc='utf-8'):
     # FIXME: atm some important information is dropped from the original result -> make sure it is transferred to the new one
     try:
         super().set_progress(current, total, description)
     except IntegrityError as exp:
         if hasattr(settings, 'CELERY_TASK_ALWAYS_EAGER'
                    ) and settings.CELERY_TASK_ALWAYS_EAGER:
             return
         else:
             raise exp
     percent = 0
     if total > 0:
         percent = (Decimal(current) / Decimal(total)) * Decimal(100)
         percent = float(round(percent, 2))
     TaskResult.objects.store_result(
         ctype,
         cenc,
         self.task.request.id,
         json.dumps({
             'current': current,
             'total': total,
             'percent': percent,
             'description': description
         }),
         celery_progress.backend.PROGRESS_STATE,
         task_name=self.task.name,
     )
Beispiel #8
0
def Fisher():

    sad = round(
        m * ((y1 - ymed[0])**2 + (y2 - ymed[1])**2 + (y3 - ymed[2])**2 +
             (y4 - ymed[3])**2) / (4 - d), 2)
    froz = round(sad / disp, 2)

    f4 = N - d

    fkr = Decimal(abs(scipy.stats.f.isf(q, f4, f3))).quantize(
        Decimal('.0001')).__float__()

    print("\n3)Критерій Фішера:\n")
    print("   f4 = {2} - {0} = {1}".format(d, f4, N))
    print(
        "   {0}*(({5} - {1})**2 + ({6} - {2})**2 + ({7} - {2})**2 + ({8} - {2})**2)/(4-{10}) = {9}"
        .format(m, *ymed, y1, y2, y3, y4, sad, d))
    print("   Fр = {0}/{1} = {2}".format(sad, disp, froz))
    print("   За таблицею Fкр =", fkr)
    if fkr > froz:
        print(
            "   За критерієм Фішера рівняння регресії адекватне оригіналу з ймовірністю",
            p)
    else:
        print(
            "   За критерієм Фішера рівняння регресії неадекватне оригіналу з ймовірністю",
            p)
def accuracyOfSeal(predictCompantNo, arrayToPredict):
    test_featureArray = arrayToPredict
    print("test array")
    print(test_featureArray)
    testFeatureArray_mean = np.mean(test_featureArray)
    print("test mean")
    print(testFeatureArray_mean)
    print("predict mean")

    predictFeatureArray_mean = getTargetSealList(predictCompantNo)
    print("predict value")
    print(predictFeatureArray_mean)
    multiValue = (Decimal(testFeatureArray_mean - predictFeatureArray_mean)*Decimal(testFeatureArray_mean - predictFeatureArray_mean))
    print("multivalue")
    print(multiValue)
    squareRootValue =format(math.sqrt(multiValue))
    print("squroot")
    print(squareRootValue)
    #squareRootValue = math.sqrt((testFeatureArray_mean - predictFeatureArray_mean) * (testFeatureArray_mean - predictFeatureArray_mean))
    testFeatureArray_mean = format(testFeatureArray_mean, '.6f')
    division = float(squareRootValue) / float(predictFeatureArray_mean)
    # print("dive")
    # print(format(dive,'.7f'))
    # print(format(((math.sqrt((m1-m2)*(m1-m2)))//m1),'.6f'))
    # print((dive)*100)
    accuracy = ((1.0 - division) * 100)
    print("Accuracy")
    print(accuracy)
    return accuracy
Beispiel #10
0
 def test_div(self, data):
     try:
         c = Decimal(str(data["a"])) / Decimal(str(data["b"]))
         assert c == Decimal(str(data["expect"]))
     except Exception as e:
         print(e)
         raise e
def find_secret_code(k, poly, shares, master_shares):
    # Combines shares using
    # Lagranges interpolation.
    # Shares is an array of shares
    # being combined
    master_poly = find_our_secret(poly)
    our_master = master_poly(1)

    # Append our master share into the list of shares
    master_shares.insert(0, [1, (sum(shares) + our_master)])

    if (len(master_shares) < k):
        print("\n____Too few secrets for scheme____")
        return 0

    sums, prod_arr = 0, []

    # Refrence: https://www.geeksforgeeks.org/implementing-shamirs-secret-sharing-scheme-in-python/

    for j in range(len(master_shares)):
        xj, yj = master_shares[j][0], master_shares[j][1]
        prod = Decimal(1)

        for i in range(len(master_shares)):
            xi = master_shares[i][0]
            if i != j: prod *= Decimal(Decimal(xi) / (xi - xj))

        prod *= yj
        sums += Decimal(prod)

    return int(round(Decimal(sums), 0))
Beispiel #12
0
    def Student(self, N):
        self.d = N
        self.dvidtv = round(sum(self.ydisplist) / N, self.round)
        dkoef = round(self.d / (N * self.m), self.round)
        skoef = round(sqrt(dkoef), self.round)

        t0 = round(fabs(self.alist[0]) / skoef, self.round)
        t1 = round(fabs(self.alist[1]) / skoef, self.round)
        t2 = round(fabs(self.alist[2]) / skoef, self.round)
        t3 = round(fabs(self.alist[3]) / skoef, self.round)
        if N == 8:
            t12 = round(fabs(self.alist[4]) / skoef, self.round)
            t13 = round(fabs(self.alist[5]) / skoef, self.round)
            t23 = round(fabs(self.alist[6]) / skoef, self.round)
            t123 = round(fabs(self.alist[7]) / skoef, self.round)
            self.tlist = [t0, t1, t2, t3, t12, t13, t23, t123]
        else:
            self.tlist = [t0, t1, t2, t3]

        self.f3 = self.f1 * self.f2
        tkr = Decimal(abs(t.ppf(self.q / 2, self.f3))).quantize(
            Decimal('.0001')).__float__()
        for troz in self.tlist:
            if troz < tkr:
                self.blist[self.tlist.index(troz)] = 0
                self.d -= 1
        blist = self.blist
        xlist = self.xlist
        if N == 8:
            self.yznachlist = []
            xmatr = self.xmatr
            for i in range(N):
                self.yznachlist.append(
                    round(
                        blist[0] + blist[1] * xmatr[i][0] +
                        blist[2] * xmatr[i][1] + blist[3] * xmatr[i][2] +
                        blist[4] * xmatr[i][0] * xmatr[i][1] +
                        blist[5] * xmatr[i][0] * xmatr[i][2] +
                        blist[6] * xmatr[i][1] * xmatr[i][2] +
                        blist[7] * xmatr[i][0] * xmatr[i][1] * xmatr[i][2],
                        self.round))
        else:
            y1 = round(
                blist[0] + blist[1] * xlist[0][0] + blist[2] * xlist[1][0] +
                blist[3] * xlist[2][0], self.round)
            y2 = round(
                blist[0] + blist[1] * xlist[0][0] + blist[2] * xlist[1][1] +
                blist[3] * xlist[2][1], self.round)
            y3 = round(
                blist[0] + blist[1] * xlist[0][1] + blist[2] * xlist[1][0] +
                blist[3] * xlist[2][1], self.round)
            y4 = round(
                blist[0] + blist[1] * xlist[0][1] + blist[2] * xlist[1][1] +
                blist[3] * xlist[2][0], self.round)
            self.yznachlist = [y1, y2, y3, y4]
        self.skoef = skoef
        self.dkoef = dkoef
        self.tkr = tkr
        Task.printstud(N)
 def get_cohren_value(size_of_selections, qty_of_selections, significance):
     from _pydecimal import Decimal
     from scipy.stats import f
     size_of_selections += 1
     partResult1 = significance / (size_of_selections - 1)
     params = [partResult1, qty_of_selections, (size_of_selections - 1 - 1) * qty_of_selections]
     fisher = f.isf(*params)
     result = fisher / (fisher + (size_of_selections - 1 - 1))
     return Decimal(result).quantize(Decimal('.0001')).__float__()
Beispiel #14
0
def earned_points_greater_burned_points(burned_points, user):
    try:
        summary = Summary.objects.get(user=user)
        if Decimal(summary.balance_points) >= Decimal(burned_points):
            return True
    except Summary.DoesNotExist:
        pass

    return False
Beispiel #15
0
 def cohrenValue(selectionSize, selectionQty, significance):
     selectionSize += 1
     partResult1 = significance / (selectionSize - 1)
     params = [
         partResult1, selectionQty, (selectionSize - 1 - 1) * selectionQty
     ]
     fisher = f.isf(*params)
     result = fisher / (fisher + (selectionSize - 1 - 1))
     return Decimal(result).quantize(Decimal('.0001')).__float__()
Beispiel #16
0
 def get_cohren_value(self):
     size_of_selections = self.N + 1
     qty_of_selections = self.m - 1
     significance = self.q
     partResult1 = significance / (size_of_selections - 1)
     params = [partResult1, qty_of_selections, (size_of_selections - 1 - 1) * qty_of_selections]
     fisher = f.isf(*params)
     result = fisher / (fisher + (size_of_selections - 1 - 1))
     return Decimal(result).quantize(Decimal('.0001')).__float__()
Beispiel #17
0
def test_hedge():
    enter_price = Decimal('989')
    target_price = Decimal('-1012')
    prior_pos = Position(pos=Decimal('0.07'),
                         price=Decimal('1020'),
                         side=Side.BID)

    #hedge over other side
    hedge_pos = hedge_position(prior_pos, target_price, enter_price)

    print("---------------- hedge over other side")
    print("prior " + str(prior_pos))
    print("hedge " + str(hedge_pos))
    print("fin " + str(prior_pos + hedge_pos))

    #hedge over same side
    hedge_pos = hedge_position(prior_pos, target_price, Decimal('-1011'))
    print("---------------- hedge over same side")
    print("prior " + str(prior_pos))
    print("hedge " + str(hedge_pos))
    print("fin " + str(prior_pos + hedge_pos))

    #from reality
    prior_pos = Position(pos=Decimal('0.07'),
                         price=Decimal('1131.2700'),
                         side=Side.ASK)
    hedge_pos = hedge_position(prior_pos, Decimal('-1159.2805'),
                               Decimal('1161.4102'))
    print("---------------- real situation")
    print("prior " + str(prior_pos))
    print("hedge " + str(hedge_pos))
    print("fin " + str(prior_pos + hedge_pos))


#test_hedge()
Beispiel #18
0
def get_total_price(user):

    carts = Cart.objects.filter(c_user=user).filter(c_is_select=True)

    total = 0

    for cart in carts:
        total += cart.c_goods_num * cart.c_goods.price

    # Decimal用于精准计算  Decimal('0.00')表示保留小数点后两位 ROUND_HALF_UP四舍五入
    total = str(Decimal(total).quantize(Decimal('0.00'), ROUND_HALF_UP))
    return total
Beispiel #19
0
 def build():
     hc = healthcan()
     now = datetime.datetime.now(pytz.timezone('Asia/Tokyo'))
     hc.attr["date"] = '{0:%Y-%m-%d}'.format(now.date())
     hc.attr["time"] = '{0:%H:%M:%S}'.format(now.time())
     hc.attr["height"] = Decimal(0)
     hc.attr["weight"] = Decimal(0)
     hc.attr["bmi"] = Decimal(0)
     hc.attr["pro_weight"] = Decimal(0)
     hc.attr["diff_weight"] = Decimal(0)
     
     return hc
Beispiel #20
0
def Student():
    global znach, y1, y2, y3, y4, disp, d
    disp = round(sum(ydisp) / 4, 2)
    dbs = round(d / (4 * m), 2)
    sbs = round(sqrt(dbs), 2)

    t0 = round(fabs(my) / sbs, 2)
    t1 = round(fabs(a1) / sbs, 2)
    t2 = round(fabs(a2) / sbs, 2)
    t3 = round(fabs(a3) / sbs, 2)
    tlist = [t0, t1, t2, t3]
    tkr = Decimal(abs(scipy.stats.t.ppf(q / 2, f3))).quantize(
        Decimal('.0001')).__float__()

    for troz in tlist:
        if troz < tkr:
            b[tlist.index(troz)] = 0
            d -= 1

    y1 = round(b[0] + b[1] * x1min + b[2] * x2min + b[3] * x3min, 2)
    y2 = round(b[0] + b[1] * x1min + b[2] * x2max + b[3] * x3max, 2)
    y3 = round(b[0] + b[1] * x1max + b[2] * x2min + b[3] * x3max, 2)
    y4 = round(b[0] + b[1] * x1max + b[2] * x2max + b[3] * x3min, 2)

    print("\n2)Критерій Стьюдента:\n")
    print("   Dвідтворюваності = ({0}+{1}+{2}+{3})/4 = {4}".format(
        *ydisp, disp))
    print(
        "   D{{bi}} = {0}/(4*{1}) = {2}\n   S{{bi}} = sqrt({2}) = {3}".format(
            disp, m, dbs, sbs))
    print(
        "   t0 = |{0}|/{4} = {5}\n   t1 = |{1}|/{4} = {6}\n   t2 = |{2}|/{4} = {7}\n   \
t3 = |{3}|/{4} = {8}\n   ".format(my, a1, a2, a3, sbs, *tlist))
    print("   f3 = 4*({0}-1) = {1}\n   За таблицею tkr = {2}".format(
        m, f3, tkr))
    for i in range(4):
        if tlist[i] < tkr:
            print(
                "   {0} < {1} => За критерієм Стьюдента коефіцієнт b{2} статистично незначущий з ймовірністю {3}"
                .format(tlist[i], tkr, i, p))
        else:
            print(
                "   {0} > {1} => За критерієм Стьюдента коефіцієнт b{2} статистично значимий з ймовірністю {3}"
                .format(tlist[i], tkr, i, p))
    print("\n   {0} + {1}*{4} + {2}*{5} + {3}*{6} = {7}".format(
        *b, x1min, x2min, x3min, y1))
    print("   {0} + {1}*{4} + {2}*{5} + {3}*{6} = {7}".format(
        *b, x1min, x2max, x3max, y2))
    print("   {0} + {1}*{4} + {2}*{5} + {3}*{6} = {7}".format(
        *b, x1max, x2min, x3max, y3))
    print("   {0} + {1}*{4} + {2}*{5} + {3}*{6} = {7}".format(
        *b, x1max, x2max, x3min, y4))
Beispiel #21
0
def get_pay_total_price(orderid):

    order = Order.objects.get(pk=orderid)

    goods_list = order.ordergoods_set.all()

    total = 0
    for goods in goods_list:
        total += goods.o_goods.price * goods.o_goods_num

    total = str(Decimal(total).quantize(Decimal('0.00'), ROUND_HALF_UP))

    return total
Beispiel #22
0
    def get_cohren_value(size_of_selections, qty_of_selections, significance):
        # qty_of_selections = 4
        # size_of_selections = 4
        size_of_selections += 1

        #  significance = 0.05

        partResult1 = significance / (size_of_selections - 1)
        params = [partResult1, qty_of_selections, (size_of_selections - 1 - 1) * qty_of_selections]
        fisher = f.isf(*params)
        # print(fisher)
        # fisher = 0
        result = fisher / (fisher + (size_of_selections - 1 - 1))
        return Decimal(result).quantize(Decimal('.0001')).__float__()
Beispiel #23
0
class Contract(models.Model):
    price = models.DecimalField(
        decimal_places=0,
        max_digits=12,
        validators=[MinValueValidator(Decimal('0.01'))],
        null=True,
        blank=True)
    signing_date = models.DateField(null=True, blank=True)
    activation_date = models.DateField(null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True)
    duration = models.DecimalField(
        decimal_places=0,
        max_digits=12,
        validators=[MinValueValidator(Decimal('0.01'))],
        null=True,
        blank=True)
    tariff = models.ForeignKey("Tariff",
                               on_delete=models.SET_NULL,
                               null=True,
                               blank=True)
    tariff_price = models.DecimalField(
        decimal_places=0,
        max_digits=12,
        validators=[MinValueValidator(Decimal('0.01'))],
        null=True,
        blank=True)
    description = models.CharField(max_length=255)

    @property
    def sphere(self):
        return 'Contract'

    class Meta:
        db_table = 'contracts'
        ordering = ['id']

    def __str__(self):
        return self.description

    def paid(self):
        paid_cash = 0
        for payment in self.payment_set.all().values('cash'):
            paid_cash += int(payment['cash'])
        return paid_cash

    def debt(self):

        return int(self.price) - self.paid()
def animateLast24HoursConductivity(i):
    pullData = open(DataFilePathConductivity, "r").read()
    dataList = pullData.split('\n')
    xList = []
    yList = []
    fmt = '%Y-%m-%d %H:%M:%S.%f'
    for eachLine in dataList:
        if len(eachLine) > 1:
            date, cond = eachLine.split(',')
            timestamp1 = datetime.strptime(date, fmt)
            timestamp2 = datetime.strptime(str(datetime.now()), fmt)
            interval = (timestamp2 - timestamp1)
            if interval.days <= 1:
                date, time = date.split(' ')
                hour, minute, second = time.split(':')
                xAxisDateTime = str(timestamp1.date()) + " " + str(timestamp1.hour) + ":00"
                xList.append(xAxisDateTime)
                yList.append(Decimal(cond))

                pltLast24HoursConductivity.clear()
                pltLast24HoursConductivity.set_title(str(timestamp1.date().year) + " Conductivity Graph")
                pltLast24HoursConductivity.set_ylabel("Conductivity (uS/Cm)")

                pltLast24HoursConductivity.set_xlabel("Hour Wise Data ")

                pltLast24HoursConductivity.scatter(xList, yList, marker='.')
                last24HoursFigureConductivity.autofmt_xdate()
def animateLastYearTemperature(i):
    pullData = open(DataFilePathTemperature, "r").read()
    dataList = pullData.split('\n')
    xList = []
    yList = []
    fmt = '%Y-%m-%d %H:%M:%S.%f'

    for eachLine in dataList:
        if len(eachLine) > 1:
            date, temp = eachLine.split(',')
            timestamp1 = datetime.strptime(date, fmt)
            timestamp2 = datetime.strptime(str(datetime.now()), fmt)
            interval = (timestamp2 - timestamp1)
            if interval.days <= 365:
                date, time = date.split(' ')
                xAxisDateTime = str(timestamp1.date().year) + " " \
                                + timestamp1.date().strftime('%b')
                xList.append(xAxisDateTime)
                yList.append(Decimal(temp))
                pltLastYearTemperature.clear()
                pltLastYearTemperature.set_title(str(timestamp1.date().year) + " Temperature Graph")
                pltLastYearTemperature.set_ylabel("Temperature (Degrees Celcius)")
                pltLastYearTemperature.set_xlabel("Month Wise Data ")

                pltLastYearTemperature.scatter(xList, yList, marker='.')
                lastYearFigureTemperature.autofmt_xdate()
Beispiel #26
0
 def fishers(self, N):
     dadekv = 0
     Nroz = N
     for k in range(N):
         dadekv += (self.yznachlist[k] - self.ymed[k])**2
     if N == self.d:
         Nroz = N + 1
         self.Nroz = Nroz
     dadekv = round((dadekv * m) / (Nroz - self.d), self.round)
     froz = round(dadekv / self.dvidtv, self.round)
     self.f4 = Nroz - self.d
     fkr = Decimal(abs(f.isf(self.q, self.f4, self.f3))).quantize(
         Decimal('.0001')).__float__()
     self.dadekv = dadekv
     self.froz = froz
     self.fkr = fkr
     Task.printfish(N)
     if froz > fkr:
         if N == 14:
             print(
                 "   За критерієм Фішера рівняння з квадратичними членами неадекватне оригіналу з ймовірністю\n\n",
                 p)
         else:
             print(
                 "   За критерієм Фішера лінійне рівняння неадекватне оригіналу з ймовірністю\n\n",
                 p)
             if N == 4:
                 N = 8
                 print(
                     "\nПроведемо досліди для рівняння з ефектом взаємодії, тоді N =",
                     N)
             elif N == 8:
                 N = 14
                 print(
                     "\nПроведемо досліди для рівняння з квадратичними членами, тоді N =",
                     N)
             Task.equation(N, m)
             Task.cochran(N, m)
             Task.student(N)
             Task.fishers(N)
     else:
         print(
             "   За критерієм Фішера лінійне рівняння регресії адекватне оригіналу з ймовірністю\n\n",
             p)
Beispiel #27
0
    def setUp(self):
        self.hc = healthcan()
        now = datetime.datetime.now(pytz.timezone('Asia/Tokyo'))
        self.hc.attr["user_id"] = 1
        self.hc.attr["name"] = "HogeFuga"
        self.hc.attr["date"] = '{0:%Y-%m-%d}'.format(now.date())
        self.hc.attr["time"] = '{0:%H:%M:%S}'.format(now.time())
        self.hc.attr["height"] = Decimal(175.0)
        self.hc.attr["weight"] = Decimal(68.0)
        self.hc.attr["bmi"] = Decimal(22.2)
        self.hc.attr["pro_weight"] = Decimal(67.38)
        self.hc.attr["diff_weight"] = Decimal(0.63)

        patcher = mock.patch('model.healthcan.project.name',
                             return_value="mock_healthcan")
        self.mock_name = patcher.start()
        self.addCleanup(patcher.stop)
        healthcan.migrate()
        self.hc.save()
    def col_default(column_value: str):
        if column_value.strip() in CSV_NULL_VALUES:
            return None

        if '$' in column_value or '%' in column_value:
            try:
                Decimal(RowTypeAggregator.str_to_decimal(column_value))
                return Decimal()
            except DecimalException:
                pass
        try:
            int(column_value)
            return int(0)
        except ValueError:
            pass
        try:
            float(column_value)
            return float(0.0)
        except ValueError:
            return str('-')
Beispiel #29
0
def elapsed(t0=0.0):
    """
    Get the elapsed time from the give time.
    If the start time is not given, returns the unix-time.

    Returns
    -------
    t : float
        Elapsed time from the given time; Otherwise the epoch time.
    s : str
        The elapsed time in seconds in a string
    """
    t = time()
    dt = t - t0
    dt_sec = Decimal(str(dt)).quantize(Decimal('.0001'), rounding=ROUND_DOWN)
    if dt_sec == 1:
        s = str(dt_sec) + ' second'
    else:
        s = str(dt_sec) + ' seconds'
    return t, s
Beispiel #30
0
def heuristic1(clauses, truthvalues):
    choice = clauses[0][0]
    best_total = 0
    for literal in truthvalues:
        if truthvalues[literal] is None:
            pos_score = 0
            neg_score = 0
            for clause in clauses:
                if literal in clause:
                    pos_score += Decimal(2 ** -len(clause))
                elif -literal in clause:
                    neg_score += Decimal(2 ** -len(clause))
            # Keep track of the best score.
            if (pos_score + neg_score) > best_total:
                best_total = pos_score + neg_score
                # Choose the positive or negative literal (the most occuring).
                if pos_score >= neg_score:
                    choice = literal
                else:
                    choice = -literal
    return choice