Recursive program to compute Taylor approx of cosine not functioning in Prolog

前端 未结 2 1465
遇见更好的自我
遇见更好的自我 2021-01-22 15:36

I\'m still pretty new to Prolog, and i\'m not sure why this code isn\'t working. I believe it is most likely a problem with the base case or in the last 3 lines of the recursive

2条回答
  •  攒了一身酷
    2021-01-22 15:51

    Base case was wrong, should've been cosN(N,N,_,0). as K and N must both be equal to N when the program is finished the recursive process.

    Test cases:

    :- begin_tests(cosine_approximation).
    
    factorial_test_case_generator(0,1).
    factorial_test_case_generator(1,1).
    factorial_test_case_generator(2,2).
    factorial_test_case_generator(3,6).
    factorial_test_case_generator(4,24).
    factorial_test_case_generator(5,120).
    factorial_test_case_generator(6,720).
    factorial_test_case_generator(7,5040).
    factorial_test_case_generator(8,40320).
    factorial_test_case_generator(20,2432902008176640000).
    
    test('factorial',[nondet,forall(factorial_test_case_generator(N,Factorial))]) :-
        fact(N,Factorial).
    
    signCnt_test_case_generator(0,1).
    signCnt_test_case_generator(1,-1).
    signCnt_test_case_generator(2,1).
    signCnt_test_case_generator(3,-1).
    signCnt_test_case_generator(4,1).
    signCnt_test_case_generator(5,-1).
    
    test('signCnt',[nondet,forall(signCnt_test_case_generator(N,Sign))]) :-
        signCnt(N,Sign).
    
    cosN_test_case_generator(3,pi/2,0.01996895776487828).
    cosN_test_case_generator(5,pi,-0.9760222126236076).
    cosN_test_case_generator(25,pi,-1.0).
    cosN_test_case_generator(10,pi/2,-3.3306690738754696e-15).
    
    test('cosN',[nondet,forall(cosN_test_case_generator(N,X,Y))]) :-
        cosN(N,X,Y).
    
    :- end_tests(cosine_approximation).
    

    Example run:

    ?- make.
    % /Users/oliverclarke/prolog/lab5-quiz compiled 0.00 sec, 3 clauses
    % PL-Unit: cosine_approximation .................... done
    % All 20 tests passed
    true.
    

提交回复
热议问题