2016-06-23 3 views
0

깃발의 영역 Building Skills with Python을 푸는 시도. 나는 푸른 지역을 해결하려고 노력하고 있는데, 나는 약 2 % 정도 벗어났다. 또한 다른 지역을 합하면 합계가 국기 자체의 면적과 같지 않습니다.파이썬 - 깃발의 영역

import math 


def area_star(width): 
    a = 36.00 
    b = 72.00 

    radius_star = 0.0308 * width 

    a_radians = float(a) * float(math.pi)/float(180) 
    b_radians = float(b) * float(math.pi)/float(180) 

    a_sin = math.sin(float(a_radians)/float(2)) 
    b_sin = math.sin(float(b_radians)/float(2)) 

    top = a_sin*b_sin 

    c_radians = float((a+b)*math.pi)/float(180) 
    c_sin = math.sin(c_radians) 

    bottom = 0.5 * c_sin  
    return 5 * float(top)/float(bottom) * radius_star * radius_star 
def fifty_stars(width): 
    return 50 * area_star(width) 
def calculate_areas(width): 
    WIDTH = width 
    length = 1.9 * WIDTH 
    width_union = float(7)/float(13) * WIDTH 
    length_union = 0.76*WIDTH 
    NUMBER_RED_STRIPES = 7 
    NUMBER_WHITE_STRIPES = 6 

    width_strip_denom = NUMBER_RED_STRIPES+NUMBER_WHITE_STRIPES 
    width_strip = float(1)/float(width_strip_denom)*WIDTH 

    blue_area = length_union * width_union - fifty_stars(WIDTH) 
    white_area = 3 * width_strip * (length*length_union)+3*width_strip*length+fifty_stars(WIDTH) 
    red_area = 4 * width_strip*(length*length_union)+3*width_strip*length 




    print 'Our width was given as : %f' %WIDTH 
    print 'Our length calculates as : %f' %length 

    print 'Width of our union is: %f' %width_union 
    print 'Length of our union is: %f' %length_union 

    print 'Area of a star is %f'%area_star(WIDTH) 
    print 'Area of 50 stars is %f'%fifty_stars(WIDTH) 

    print 'Area of our flag in total is : %f '%(WIDTH*length) 
    print 'Actual WHITE AREA is %f'%white_area 
    print 'Actual RED AREA is %f'%red_area 
    print 'Expected BLUE AREA is %f' %(WIDTH*length*.1873) 
    print 'Actual BLUE AREA is %f'%blue_area 

    print 'SumofallAreas: %f' % (red_area+white_area+blue_area) 



calculate_areas(1.0) 

내 출력은 다음과 같습니다 :

Our hoist was given as : 1.000000 
Our length calculates as : 1.900000 
Width of our union is: 0.538462 
Length of our union is: 0.760000 
Area of a star is 0.001812 
Area of 50 stars is 0.090587 
Area of our flag in total is : 1.900000 
Actual WHITE AREA is 0.792126 
Actual RED AREA is 0.789231 
Expected BLUE AREA is 0.355870 
Actual BLUE AREA is 0.318644 
SumofallAreas: 1.900000 

설명 할 수 플로트에 대해 뭔가가 분산 있는가 또는 내 코드 자체에 문제가 다음과 같이 내 코드는?

는 ********* 업데이트 된 코드 PER은

import math 
from fractions import Fraction 

def area_star(width): 
    a = 36.00 
    b = 72.00 

    radius_star = 0.0308 * width 

    a_radians = float(a) * float(math.pi)/float(180) 
    b_radians = float(b) * float(math.pi)/float(180) 

    a_sin = math.sin(float(a_radians)/float(2)) 
    b_sin = math.sin(float(b_radians)/float(2)) 

    top = a_sin*b_sin 

    c_radians = float((a+b)*math.pi)/float(180) 
    c_sin = math.sin(c_radians) 

    bottom = 0.5 * c_sin  
    return 5 * float(top)/float(bottom) * radius_star * radius_star 

def fifty_stars(width): 
    return 50 * area_star(width) 

def calculate_areas(width): 
    hoist = width 
    fly = hoist * Fraction(19,10) 

    jack_hoist = Fraction(7,13) * hoist 
    jack_fly = Fraction(76,100)*hoist 

    NUMBER_RED_STRIPES = 7 
    NUMBER_WHITE_STRIPES = 6 

    width_strip_denom = NUMBER_RED_STRIPES+NUMBER_WHITE_STRIPES 
    width_strip = Fraction(1,width_strip_denom)*hoist 

    blue_area = jack_fly * jack_hoist - fifty_stars(hoist) 
    white_area = 3 * width_strip * (fly-jack_fly)+3*width_strip*fly+fifty_stars(hoist) 
    red_area = 4 * width_strip*(fly-jack_fly)+3*width_strip*fly 




    print 'Our hoist was given as : %f' %hoist 
    print 'Our length calculates as : %f' %fly 

    print 'Width of our union is: %f' %jack_hoist 
    print 'Length of our union is: %f' %jack_fly 

    print 'Area of a star is %f'%area_star(hoist) 
    print 'Area of 50 stars is %f'%fifty_stars(hoist) 

    print 'Area of our flag in total is : %f '%(hoist*fly) 
    print 'Actual WHITE AREA is %f'%white_area 
    print 'Actual RED AREA is %f'%red_area 
    print 'Expected BLUE AREA is %f' %(hoist*fly*.1873) 
    print 'Actual BLUE AREA is %f'%blue_area 

    print 'SumofallAreas: %f' % (red_area+white_area+blue_area) 



calculate_areas(1.0) 
+0

[? 소수점 연산이 깨진 떠]의 사용 가능한 복제 (http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Aidan

+0

문제점 설명과 일치하는 변수를 사용하면 감사하는 것이 더 쉬울 것입니다. 예를 들어'Wf = 1.0 '이다. –

+0

변수를 업데이트하고 분수 함수를 추가했습니다. 합계를 조정하려면 합계를 합계하지만 BLUE_AREA는 아직 꺼져 있습니다 ?? – Jeeves

답변

2

여기 내 계산입니다. 원래 문제는 아래의 주석에 오류가 기록되어있었습니다.

참고 :from __future__ 파이썬 2와 같은 1/2 = 0.5이 아닌 0이 수학을 정리 파이썬 3, 같은 분할 작업을합니다.

또한 문제 문과 동일한 변수를 사용하면 수식을 입력하고 확인하는 것이 더 쉬워졌습니다. 나는 K의 두 가지 버전이 같은 대답을주지 않았기 때문에 문제를 독립적으로 해결했고 5*K의 황금 비율 버전이 내가 별의 영역에서했던 것과 같은 대답을 얻는 것을 발견했다.

from __future__ import division 
from math import sin,pi 

Wf = 1.0 
Lf = 1.9 * Wf 
A = Wf * Lf 
Wu = 7/13 * Wf 
Lu = .76 * Wf 
R = .0308 * Wf 
Sr = 7 
Sw = 6 
Ns = 50 
Ws = 1/(Sr+Sw) * Wf 

a = 36 * pi/180 
b = 72 * pi/180 
GR = (1 + 5**.5)/2 
K = sin(b/2)/GR**2 * (R**2) # Golden ratio version of K was correct, other was wrong. 
S = 5 * K 

Red = 4 * Ws * (Lf - Lu) + 3 * Ws * Lf 
White = 3 * Ws * (Lf - Lu) + 3 * Ws * Lf + Ns * S 
Blue = (Lu * Wu) - Ns * S # Error on problem page used (Lu - Wu) 

print('Red =',Red) 
print('White =',White) 
print('Blue =',Blue) 
print('total =',Red+White+Blue) 
print('Red = {:%}'.format(Red/A)) 
print('White = {:%}'.format(White/A)) 
print('Blue = {:%}'.format(Blue/A)) 

출력 :

Red = 0.7892307692307692 
White = 0.7547841990012687 
Blue = 0.355985031767962 
total = 1.9 
Red = 41.538462% 
White = 39.725484% 
Blue = 18.736054% 
+0

감사합니다. 밤에 전화를 걸기 전에 두 번째 수식을보고 있었는데 다른 값을 가지고 있다는 것을 알았습니다. 이 변형 수식을 보완하기 위해 원본을 수정했습니다. 서로 다른 사용 사례가 아닌 한 서로 다른 결과를 산출하는 두 가지 수식을 나열하는 이유를 잘 모릅니다. – Jeeves

+0

@Jeeves 전 계산에서 단지 오류라고 생각하거나 아니면 곱하기 대신 뺄셈을 사용하는 파란색 영역 수식과 같은 또 다른 오타라고 생각합니다. 실수를 결정하는 첫 번째 수식을 도출하려고하지 않았습니다. –

-3

파이썬이 문제가 부동 다루는 것으로 알려져있다 ***************** 제안 포인트 작업. 는 또한 동일/유사한 문제를 Python rounding error with float numbers [duplicate]

+0

비슷한/동일한 게시물을 연결하는 경우 – Li357

+0

으로 표시하십시오. – Aidan

+0

이라는 문자 그대로 중복 된 것으로 표시됩니다. 원래 게시물의 중복으로이 게시물을 표시하는 이유가 더 있습니다 – Li357

0

부동 소수점 정밀도 문제를 해결 이전 스택이 계산이 너무 크게 꺼져 원인이되지 않습니다

다음은 Floating Point Arithmetic: Issues and Limitations

편집에 대한 자세한 내용입니다. 방금 코드에 버그가 있습니다. 특히 출력에서 ​​Expected BLUE AREA is 0.355870Actual BLUE AREA is 0.318644은 상당히 다른 계산을 사용하기 때문에 발생합니다.

잠깐 살펴볼 수있는 문제점 : 나는 width_unionlength_union을 모두 플래그의 너비에 비례해서 계산해야합니까?

추가 버그가있을 수 있습니다. 많은 "마법 번호"가 코드 전체에 흩어져있어보기가 어렵습니다 (예 : float(7)/float(13), 0.76).

+0

"마법"숫자가 무엇인지 잘 모르겠습니다. 도움을 청할 수 있도록 노력했습니다. 수식은 링크에서 직접적으로 설명됩니다. – Jeeves

+0

"매직 넘버"는 코드에서 설명없이 나타나는 숫자입니다. 일반적으로'AspectRatio = 1.9','StripeCount = 13','RedStripes = 7','StarRadius = 0.4 * StripeHoist' 등 상판에 상수로 입력하는 것이 더 낫습니다. –

+0

일반적으로 상수를 맨 위로 올리고, 그러나 그는 단지 운동이었습니다. 그러나 이제는 '마법의 숫자'가 무엇인지 알고 있습니다. 그리고 암소로 바꾸어서는 안됩니다! – Jeeves

0

먼저 '길이'와 '너비'를 혼동 할 수 있습니다. '깃대에 평행 한 차원'과 '플라이'(깃대에 수직 인 차원)를 사용하는 것이 더 낫습니다.

둘째, 숫자가 꺼져 있습니다. 높은 스트라이프를 날다가 length*length_union을 사용하고 있지만 올바르지 않습니다. length_union은 파리의 비율이 아니라 호이스트의 비율이 아니라 이미 곱 해져 있으므로 다시 곱하면 안됩니다. 어쨌든, 당신은 광저우의 파리는 원하지 않지만, 총 파리는 마이너스 주야입니다.

나머지 수학은 확인하지 않았지만 length*length_union 대신 length-length_union을 사용하면 더 좋은 결과를 얻을 수 있습니다.

별을 무시하면 디버깅하는 데 도움이되는 경우 이러한 영역이 표시됩니다. 당신의 코드에서와 같이, 1.0은 호이스트와 같은면을 가진 정사각형 플래그의 영역입니다; 그러므로 전체 깃발은 1.9의 면적을 갖는다.

red = 513/650 (~ 0.789231) 
white stripes only = 228/325 (~ 0.701538) 
blue canton + white stars = 133/325 (~ 0.409231) 
total = (513 + 228 * 2 + 133 * 2)/650 = 1235/650 = 1.9 

별을 분석하면 파란색에서 흰색으로 일부가 이동하지만 빨강 (및 3 개 모두 합)이 변경되어서는 안됩니다.당신은 더 나은 정밀도를하고자 할 경우

, 당신은 fractions 모듈과 정확한 합리적인 계산을 사용하도록 전환 할 수 있습니다 :

from fractions import Fraction 
hoist = 1 
fly = hoist * Fraction(19,10) 
stripe_hoist = hoist * Fraction(1,13) 
canton_hoist = 7 * stripe_hoist 
canton_fly = fly * Fraction(2, 5) 

+0

제안에 감사드립니다 - 업데이트 된 var 이름이 length * length_union 길이를 length-lenght_union으로 변경했습니다. 다른 총 합계를 얻지 만 실제 blue_area 자체는 아직 꺼져 있습니다 ?? – Jeeves