Improved Evaluation
This commit is contained in:
94
MathPad/MPTerm.m
Normal file
94
MathPad/MPTerm.m
Normal file
@@ -0,0 +1,94 @@
|
||||
//
|
||||
// MPTerm.m
|
||||
// MathPad
|
||||
//
|
||||
// Created by Kim Wittenburg on 27.09.14.
|
||||
// Copyright (c) 2014 Kim Wittenburg. All rights reserved.
|
||||
//
|
||||
|
||||
#import "MPTerm.h"
|
||||
#import "MPEvaluationContext.h"
|
||||
|
||||
@interface MPTerm ()
|
||||
|
||||
@property (nonatomic, copy) NSDecimalNumber *(^block)();
|
||||
|
||||
@end
|
||||
|
||||
@implementation MPTerm
|
||||
|
||||
- (instancetype)initWithBlock:(NSDecimalNumber *(^)())block
|
||||
{
|
||||
self = [super init];
|
||||
if (self) {
|
||||
self.block = block;
|
||||
}
|
||||
return self;
|
||||
}
|
||||
|
||||
- (instancetype)initWithNumber:(NSDecimalNumber *)number
|
||||
{
|
||||
return [self initWithBlock:^NSDecimalNumber *{
|
||||
return number;
|
||||
}];
|
||||
}
|
||||
|
||||
- (instancetype)initWithSummands:(NSArray *)summands
|
||||
{
|
||||
return [self initWithBlock:^NSDecimalNumber *{
|
||||
NSDecimalNumber *value = [NSDecimalNumber zero];
|
||||
for (MPTerm *term in summands) {
|
||||
value = [value decimalNumberByAdding:[term evaluate]];
|
||||
}
|
||||
return value;
|
||||
}];
|
||||
}
|
||||
|
||||
- (instancetype)initWithFactors:(NSArray *)factors
|
||||
{
|
||||
return [self initWithBlock:^NSDecimalNumber *{
|
||||
NSDecimalNumber *value = [NSDecimalNumber one];
|
||||
for (MPTerm *term in factors) {
|
||||
value = [value decimalNumberByMultiplyingBy:[term evaluate]];
|
||||
}
|
||||
return value;
|
||||
}];
|
||||
}
|
||||
|
||||
- (instancetype)initWithVariable:(NSString *)variable
|
||||
{
|
||||
return [self initWithBlock:^NSDecimalNumber *{
|
||||
return [[MPEvaluationContext sharedContext] valueForVariable:variable];
|
||||
}];
|
||||
}
|
||||
|
||||
- (instancetype)initWithSinOfTerm:(MPTerm *)term
|
||||
{
|
||||
return [self initWithBlock:^NSDecimalNumber *{
|
||||
NSDecimalNumber *sinValue = [term evaluate];
|
||||
return [[NSDecimalNumber alloc] initWithDouble:sin(sinValue.doubleValue)];
|
||||
}];
|
||||
}
|
||||
|
||||
- (instancetype)initWithCosOfTerm:(MPTerm *)term
|
||||
{
|
||||
return [self initWithBlock:^NSDecimalNumber *{
|
||||
NSDecimalNumber *cosValue = [term evaluate];
|
||||
return [[NSDecimalNumber alloc] initWithDouble:cos(cosValue.doubleValue)];
|
||||
}];
|
||||
}
|
||||
|
||||
- (instancetype)initWithTanOfTerm:(MPTerm *)term
|
||||
{
|
||||
return [self initWithBlock:^NSDecimalNumber *{
|
||||
NSDecimalNumber *tanValue = [term evaluate];
|
||||
return [[NSDecimalNumber alloc] initWithDouble:tan(tanValue.doubleValue)];
|
||||
}];
|
||||
}
|
||||
|
||||
- (NSDecimalNumber *)evaluate
|
||||
{
|
||||
return self.block();
|
||||
}
|
||||
|
||||
@end
|
||||
Reference in New Issue
Block a user